#include "PubDataManager.h"
#include "StringConverter.h"
#include "ResourceManager.h"
#include "Database/DatabaseEnv.h"
#include "StringConverter.h"
#include "json/json.h"
#include "NGLog.h"
#include "Character.h"
#include "CharManager.h"
#include "Items.h"
#include "ItemManager.h"
#include "Users.h"
#include "UserManager.h"
#include "ChannelManager.h"
#include "ItemModelManager.h"
#include "Message.h"
#include "CenterBankManager.h"
#include "VipCardManager.h"
#include "Tools.h"
#include "XMLData.h"
#include "GameDefine.h"
#include XMLDATA_MGR_PATH
#include LOGIC_MGR_PATH
#include LOG_MGR_PATH
#include PROTOCOLS_MGR_PATH
#include "OpcodesEx.h"
#include <exception>

#include "AIInterface.h"
#include "MD5.h"

#define SERVERINFO_URL_SECRET 	"bAAoaafxnwHtk136C86332fA1DE11908578"

using namespace AIScript;

//--------------------------------------------------------
bool PubDataManager::AddPubData(GamePubData &pd)
{
	Fields fields;
	sDataMgr.initData(DataManager::DatabaseTypeCenter, DB_NAME_PUBDATA, &fields);
	// fields["pd_id"] = pd.pd_id;
	fields["group_id"] = 1;
	fields["status"] = pd.status;
	fields["type"] = pd.type;
	fields["sub_type"] = pd.sub_type;
	fields["flag"] = pd.flag;
	fields["gz_id"] = pd.gz_id;
	fields["src_gz_id"] = pd.src_gz_id;
	fields["src_id"] = pd.src_id;
	fields["src_type"] = pd.src_type;
	fields["src_platform_id"] = pd.src_platform_id;
	fields["src_nick"] = pd.src_nick;
	fields["src_addr"] = pd.src_addr;
	fields["dest_id"] = pd.dest_id;
	fields["dest_type"] = pd.dest_type;
	fields["dest_platform_id"] = pd.dest_platform_id;
	fields["dest_nick"] = pd.dest_nick;
	fields["dest_addr"] = pd.dest_addr;
	fields["ndata1"] = pd.ndata1;
	fields["ndata2"] = pd.ndata2;
	fields["ndata3"] = pd.ndata3;
	fields["ndata4"] = pd.ndata4;
	fields["sdata1"] = pd.sdata1;
	fields["sdata2"] = pd.sdata2;
	fields["sdata3"] = pd.sdata3;
	fields["sdata4"] = pd.sdata4;
	fields["desc"] = pd.desc;
	fields["info"] = pd.info;
	{
		time_t t = time(0);
		tm ttm = *localtime(&t);
		char buf[20];
		strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", &ttm);
		fields["create_time"] = String(buf);
		pd.create_time = buf;
	}	
	if (!sDataMgr.insertData(DataManager::DatabaseTypeCenter, DB_NAME_PUBDATA, &fields))
		return false;
	pd.pd_id = fields["pd_id"].GetUInt32();
	
	return true;
}
//--------------------------------------------------------
bool PubDataManager::UpdatePubData(const GamePubData &pd)
{
	Fields fields;
	fields["group_id"] = pd.group_id;
	fields["status"] = pd.status;
	fields["type"] = pd.type;
	fields["sub_type"] = pd.sub_type;
	fields["flag"] = pd.flag;
	fields["gz_id"] = pd.gz_id;
	fields["src_gz_id"] = pd.src_gz_id;
	fields["src_id"] = pd.src_id;
	fields["src_type"] = pd.src_type;
	fields["src_platform_id"] = pd.src_platform_id;
	fields["src_nick"] = pd.src_nick;
	fields["src_addr"] = pd.src_addr;
	fields["dest_id"] = pd.dest_id;
	fields["dest_type"] = pd.dest_type;
	fields["dest_platform_id"] = pd.dest_platform_id;
	fields["dest_nick"] = pd.dest_nick;
	fields["dest_addr"] = pd.dest_addr;
	fields["ndata1"] = pd.ndata1;
	fields["ndata2"] = pd.ndata2;
	fields["ndata3"] = pd.ndata3;
	fields["ndata4"] = pd.ndata4;
	fields["sdata1"] = pd.sdata1;
	fields["sdata2"] = pd.sdata2;
	fields["sdata3"] = pd.sdata3;
	fields["sdata4"] = pd.sdata4;
	fields["desc"] = pd.desc;
	fields["info"] = pd.info;
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_PUBDATA, &fields, "`pd_id` = %u", pd.pd_id);
	return count > 0;
}
#define SQLBUFER_LEN 16384
//--------------------------------------------------------
bool PubDataManager::UpdatePubData(Fields * fields, const char * QueryString, ...)
{
	char sql[SQLBUFER_LEN] = ""; 
	va_list vlist; 
	va_start(vlist, QueryString); 
	vsnprintf(sql, SQLBUFER_LEN, QueryString, vlist); 
	va_end(vlist);
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_PUBDATA, fields, sql);
	return count > 0;	
}
//--------------------------------------------------------
bool PubDataManager::UpdatePubData(const uint32 &pd_id, Fields * fields)
{
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_PUBDATA, fields, "`pd_id` = %u", pd_id);
	return count > 0;	
}
//--------------------------------------------------------
bool PubDataManager::GetPubData(const uint32 &pd_id, GamePubData *pd)
{
	assert (pd);
	FieldRows rows;
	sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_PUBDATA, &rows, "`pd_id` = %u", pd_id);
	if (rows.empty())
		return false;
	Fields fields = rows.front();
	pd->pd_id = fields["pd_id"].GetUInt32();
	pd->group_id = fields["group_id"].GetUInt32();
	pd->status = fields["status"].GetUInt32();
	pd->type = fields["type"].GetUInt32();
	pd->sub_type = fields["sub_type"].GetUInt32();
	pd->flag = fields["flag"].GetUInt32();
	pd->gz_id = fields["gz_id"].GetUInt32();
	pd->src_gz_id = fields["src_gz_id"].GetUInt32();
	pd->src_id = fields["src_id"].GetUInt32();
	pd->src_type = fields["src_type"].GetUInt32();
	pd->src_platform_id = fields["src_platform_id"].GetUInt32();
	pd->src_nick = fields["src_nick"].GetValue();
	pd->src_addr = fields["src_addr"].GetValue();
	pd->dest_id = fields["dest_id"].GetUInt32();
	pd->dest_type = fields["dest_type"].GetUInt32();
	pd->dest_platform_id = fields["dest_platform_id"].GetUInt32();
	pd->dest_nick = fields["dest_nick"].GetValue();
	pd->dest_addr = fields["dest_addr"].GetValue();
	pd->ndata1 = fields["ndata1"].GetUInt32();
	pd->ndata2 = fields["ndata2"].GetUInt32();
	pd->ndata3 = fields["ndata3"].GetUInt32();
	pd->ndata4 = fields["ndata4"].GetUInt32();
	pd->sdata1 = fields["sdata1"].GetValue();
	pd->sdata2 = fields["sdata2"].GetValue();
	pd->sdata3 = fields["sdata3"].GetValue();
	pd->sdata4 = fields["sdata4"].GetValue();
	pd->desc = fields["desc"].GetValue();
	pd->info = fields["info"].GetValue();
	pd->create_time = fields["create_time"].GetValue();
	return true;
}
//--------------------------------------------------------
uint32 PubDataManager::GetPubDataList(std::list<GamePubData> *lstPubData,const char * query,...)
{
	va_list argp;
	va_start(argp, query);
	lstPubData->clear();
	FieldRows fieldRows;
	
	char sql[SQLBUFER_LEN] = ""; 
	va_list vlist; 
	va_start(vlist, query); 
	vsnprintf(sql, SQLBUFER_LEN, query, vlist); 
	va_end(vlist);
	
	if (!sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_PUBDATA, &fieldRows, sql))
		return 0;
	
	FieldRows::iterator iter, enditer = fieldRows.end();
	for (iter = fieldRows.begin(); iter != enditer; ++ iter)
	{
		GamePubData pd;
		Fields &fields = *iter;
		pd.pd_id = fields["pd_id"].GetUInt32();
		pd.group_id = fields["group_id"].GetUInt32();
		pd.status = fields["status"].GetUInt32();
		pd.type = fields["type"].GetUInt32();
		pd.sub_type = fields["sub_type"].GetUInt32();
		pd.flag = fields["flag"].GetUInt32();
		pd.gz_id = fields["gz_id"].GetUInt32();
		pd.src_gz_id = fields["src_gz_id"].GetUInt32();
		pd.src_id = fields["src_id"].GetUInt32();
		pd.src_type = fields["src_type"].GetUInt32();
		pd.src_platform_id = fields["src_platform_id"].GetUInt32();
		pd.src_nick = fields["src_nick"].GetValue();
		pd.src_addr = fields["src_addr"].GetValue();
		pd.dest_id = fields["dest_id"].GetUInt32();
		pd.dest_type = fields["dest_type"].GetUInt32();
		pd.dest_platform_id = fields["dest_platform_id"].GetUInt32();
		pd.dest_nick = fields["dest_nick"].GetValue();
		pd.dest_addr = fields["dest_addr"].GetValue();
		pd.ndata1 = fields["ndata1"].GetUInt32();
		pd.ndata2 = fields["ndata2"].GetUInt32();
		pd.ndata3 = fields["ndata3"].GetUInt32();
		pd.ndata4 = fields["ndata4"].GetUInt32();
		pd.sdata1 = fields["sdata1"].GetValue();
		pd.sdata2 = fields["sdata2"].GetValue();
		pd.sdata3 = fields["sdata3"].GetValue();
		pd.sdata4 = fields["sdata4"].GetValue();
		pd.desc = fields["desc"].GetValue();
		pd.info = fields["info"].GetValue();
		pd.create_time = fields["create_time"].GetValue();
		lstPubData->push_back(pd);
	}
	return lstPubData->size();
}
//--------------------------------------------------------
HongHaoManager::HongHaoManager()
{
	m_lstHongBaoTop.clear();
	m_lastTOPTimer = 0;
	// m_lastHBHistoryTimer = 0;
	m_bInit = false;
}

void HongHaoManager::LoadHongBao()
{
	if (m_bInit)
		return;
	std::list<GamePubData> lstGpds;
	sPubDataMgr.GetPubDataList(&lstGpds, "`type`=%u order by `create_time` desc limit 200", PubDataManager::en_PubDataType_HongBao);
	std::list<GamePubData>::iterator iter, enditer = lstGpds.end();
	for (iter = lstGpds.begin(); iter != enditer; ++ iter)
	{
	WGS_CHN_HONGBAO_INNER_LOCK
		GamePubData &pbd = *iter;
		m_mapHongBaoHistory.insert(std::make_pair(pbd.pd_id, pbd));
	}
}
//--------------------------------------------------------
bool HongHaoManager::AwardHongBao(CharPtr &pChr, const uint32 &people, const uint32 &hbCoins, const uint32 &type, 
								const String &talk, GamePubData *phbData)
{
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if (pUser.isNull())
		return false;	
	GamePubData hb;
	hb.status = en_HongBaoStatus_Normal;
	hb.type = PubDataManager::en_PubDataType_HongBao;
	hb.sub_type = type;
	hb.flag = 1;
	hb.src_gz_id = pChr->getUInt32Field("gz_id");
	hb.src_id = pUser->getHandle();
	hb.src_type = pUser->getType();
	hb.src_platform_id = pUser->getUInt32Field("platform_id");
	hb.src_nick = pChr->getStringField("name");
	hb.src_addr = pUser->getStringField("ip");
	hb.sdata3 = pChr->getStringField("desc");
	hb.ndata1 = people;
	hb.ndata2 = hbCoins;
	hb.sdata2 = talk;
	std::list<HongBaoDetail> lstHongBaoDetail;
	BuildHongBaoList(people, hbCoins, type, lstHongBaoDetail);
	hb.sdata1 = DetailToJson(lstHongBaoDetail);
	sPubDataMgr.AddPubData(hb);
	*phbData = hb;
	{
WGS_CHN_HONGBAO_INNER_LOCK
	if (m_mapHongBaoHistory.size() >= sXmlDataMgr.GetConfXMLValue("HONGBAO_LISTMAXNUM"))
	{
		m_mapHongBaoHistory.erase(m_mapHongBaoHistory.begin());
	}
	m_mapHongBaoHistory.insert(std::make_pair(hb.pd_id, hb));
	}
	return true;
}
//--------------------------------------------------------
uint32 HongHaoManager::GrabHongBao(CharPtr &pChr, const uint32 &hbId, GamePubData *phbData)
{
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if (pUser.isNull())
		return 0;
WGS_CHN_HONGBAO_INNER_LOCK
	std::map<uint32, GamePubData>::iterator mapi = m_mapHongBaoHistory.find(hbId);
	if (mapi == m_mapHongBaoHistory.end())
		return 0;
	if (mapi->second.status != en_HongBaoStatus_Normal)
		return 0;
	uint32 getNum = 0;
	String strJson = mapi->second.sdata1;
	std::list<HongBaoDetail> lstHBDetail;
	JsonToDetail(mapi->second.sdata1, &lstHBDetail);	
	std::list<HongBaoDetail>::iterator iter, enditer = lstHBDetail.end();
	for (iter = lstHBDetail.begin(); iter != enditer; ++ iter)
	{
		HongBaoDetail &hbd = *iter;
		if (hbd.pid == 0)
		{
			hbd.pid = pUser->getUInt32Field("platform_id");
			hbd.nick = pChr->getStringField("name");
			hbd.head_url = pChr->getStringField("desc");
			getNum = hbd.hbNum;
			break;
		}
		else if (hbd.pid == pUser->getUInt32Field("platform_id"))
			return 0;
	}
	if (getNum)
	{		
		mapi->second.ndata3 += getNum;
		if (mapi->second.ndata3 >= mapi->second.ndata2)
			mapi->second.status = en_HongBaoStatus_GrabNull;
		mapi->second.sdata1 = DetailToJson(lstHBDetail);
		
		Fields field;
		field["sdata1"] = mapi->second.sdata1;
		field["ndata3"] = mapi->second.ndata3;
		field["status"] = mapi->second.status;
		sPubDataMgr.UpdatePubData(mapi->second.pd_id, &field);
	}
	*phbData = mapi->second;
	return getNum;
}
//--------------------------------------------------------
uint32 HongHaoManager::GetHongBaoHistory(std::map<uint32, GamePubData> *mapHistory, const uint32 &count)
{
	uint32 i = 0;
	mapHistory->clear();
 WGS_CHN_HONGBAO_INNER_LOCK
	std::map<uint32, GamePubData>::reverse_iterator rit, rend = m_mapHongBaoHistory.rend();
	for (rit = m_mapHongBaoHistory.rbegin(); rit != rend && i < count; ++ rit, ++i){
		mapHistory->insert(std::make_pair(rit->first, rit->second));
	}
	return mapHistory->size();
}
//--------------------------------------------------------
bool HongHaoManager::GetHongBaoDetail(const uint32 &hbId, std::list<HongBaoDetail> &lstDetail)
{
	String strJson = "";
	{
 WGS_CHN_HONGBAO_INNER_LOCK
	std::map<uint32, GamePubData>::iterator mapi = m_mapHongBaoHistory.find(hbId);
	if (mapi == m_mapHongBaoHistory.end())
		return false;
	strJson = mapi->second.sdata1;
	}
	std::list<HongBaoDetail> lstTemp;
	JsonToDetail(strJson, &lstTemp);
	std::list<HongBaoDetail>::iterator iter, enditer = lstTemp.end();
	for (iter = lstTemp.begin(); iter != enditer; ++ iter)
	{
		HongBaoDetail &hbd = *iter;
		if (hbd.pid && hbd.hbNum){
			lstDetail.push_back(hbd);
		}
	}
	
	return true;
}
//--------------------------------------------------------
void HongHaoManager::BuildHongBaoList(const uint32 &people, const uint32 &hbCoins, const uint32 &type, std::list<HongBaoDetail> &lstDetail)
{
	uint32 total = hbCoins;
	uint32 num = people;
	uint32 min = 1;
	uint32 pingjun = type ? total / num : 0;
	for (uint32 i = 1; i < num; ++i)
	{
		uint32 safe_total = (total - (num - i) * min) / (num - i);
		uint32 money = pingjun ? pingjun : rand() % safe_total + min;
		total -= money;		
		HongBaoDetail hbDetail;
		hbDetail.hbNum = money;
		lstDetail.push_back(hbDetail);
	}
	HongBaoDetail hbDetail;
	hbDetail.hbNum = total;
	lstDetail.insert(lstDetail.begin(), hbDetail);
}
//--------------------------------------------------------
void HongHaoManager::JsonToDetail(const String &strJson, std::list<HongBaoDetail> *plstHBD)
{
	plstHBD->clear();
	Json::Value root;
	Json::Reader reader;
	reader.parse(strJson, root);
	for (uint32 i = 0; i != root.size(); ++i)
	{
		HongBaoDetail hbDetail;
		Json::Value &child = root[i];
		hbDetail.pid = child["pid"].asUInt();
		hbDetail.nick = child["nick"].asString();
		hbDetail.head_url = child["head_url"].asString();
		hbDetail.hbNum = child["hbNum"].asUInt();
		plstHBD->push_back(hbDetail);
	}
}
//--------------------------------------------------------
String HongHaoManager::DetailToJson(std::list<HongBaoDetail> &plstHBD)
{
	Json::Value root;
	std::list<HongBaoDetail>::iterator iter, enditer = plstHBD.end();
	for (iter = plstHBD.begin(); iter != enditer; ++ iter)
	{
		HongBaoDetail &hbDetail = *iter;
		Json::Value val;
		val["pid"] = Json::Value(hbDetail.pid);
		val["nick"] = Json::Value(hbDetail.nick);
		val["head_url"] = Json::Value(hbDetail.head_url);
		val["hbNum"] = Json::Value(hbDetail.hbNum);
		root.append(val);
	}
	Json::StyledWriter styWriter;
	return styWriter.write(root);	
}

bool HongBaoSort(const HongBaoTop &hbt1, const HongBaoTop &hbt2)
{
	return (hbt1.hbNum > hbt2.hbNum);
}

//--------------------------------------------------------
void HongHaoManager::GetHongBaoTopList(std::list<HongBaoTop> * lstHBTop)
{
	if (!sTools.IsSameDate(m_lastTOPTimer))
	{// 没有数据
		std::map<uint32, HongBaoTop> mapTops;
		std::list<GamePubData> lstGpds;
		sPubDataMgr.GetPubDataList(&lstGpds, "`type`=%u", PubDataManager::en_PubDataType_HongBao);
		// Log.Error("HongHaoManager Test", "GetHongBaoTopList  333    size[%u]", lstGpds.size());
		std::list<GamePubData>::iterator iter, enditer = lstGpds.end();
		for (iter = lstGpds.begin(); iter != enditer; ++ iter)
		{
			GamePubData &gpd = *iter;
			std::map<uint32, HongBaoTop>::iterator mapi = mapTops.find(gpd.src_id);
			if (mapi == mapTops.end())
			{
				HongBaoTop hbt;
				hbt.pid = gpd.src_id;
				hbt.nick = gpd.src_nick;
				hbt.head_url = gpd.sdata3;
				hbt.hbNum = gpd.ndata2;
				mapTops.insert(std::make_pair(gpd.src_id, hbt));
			}
			else
			{
				mapi->second.hbNum += gpd.ndata2;
			}
		}
		Log.Error("HongHaoManager Test", "GetHongBaoTopList  444   size[%u]", mapTops.size());
		std::map<uint32, HongBaoTop>::iterator mapi, endmapi = mapTops.end();
		for (mapi = mapTops.begin(); mapi != endmapi; ++ mapi)
		{
			m_lstHongBaoTop.push_back(mapi->second);
		}
		m_lstHongBaoTop.sort(HongBaoSort);
		m_lastTOPTimer = time(0);
	}
	Log.Error("HongHaoManager Test", "GetHongBaoTopList  555   size[%u]", m_lstHongBaoTop.size());
	lstHBTop->assign(m_lstHongBaoTop.begin(), m_lstHongBaoTop.end());
}
//--------------------------------------------------------
void HongHaoManager::GetHongBaoCanGrabList(const uint32 &pid, uint8 count, std::map<uint32, GamePubData> *mapHBList)
{	
	uint32 i = 0;
 WGS_CHN_HONGBAO_INNER_LOCK
	std::map<uint32, GamePubData>::iterator mapi, endmapi = m_mapHongBaoHistory.end();
	for (mapi = m_mapHongBaoHistory.begin(); mapi != endmapi && i != count; ++ mapi, ++i)
	{
		GamePubData &gpd = mapi->second;
		if (CheckCanGrab(pid, gpd))
		{
			mapHBList->insert(std::make_pair(mapi->first, mapi->second));
		}
	}
}
//--------------------------------------------------------
bool HongHaoManager::CheckCanGrab(const uint32 &pid, const GamePubData &gpd)
{
	// Log.Error("HongHaoManager Test", "/////CheckCanGrab gpd[%u] status[%u]", gpd.pd_id, gpd.status);
	if (gpd.status != en_HongBaoStatus_Normal)
		return false;
	std::list<HongBaoDetail> lstHBD;
	JsonToDetail(gpd.sdata1, &lstHBD);
	std::list<HongBaoDetail>::iterator iter, enditer = lstHBD.end();
	for (iter = lstHBD.begin(); iter != enditer; ++ iter)
	{
		HongBaoDetail &hbd = *iter;
		// Log.Error("HongHaoManager Test", "/////CheckCanGrab hbd[%u]", hbd.pid);
		if (hbd.pid == pid)
			return false;
	}
	return true;
}
//--------------------------------------------------------
void HongHaoManager::CheckHongBaoTimeout()
{
	uint32 now_time = time(0);
	if (!m_hongbao_timeout){
		m_hongbao_timeout = now_time;
	}
	uint32 timeout = sXmlDataMgr.GetConfXMLValue("HONGBAO_CHECKTIMEOUT");
	if (!timeout)
		timeout = 60;
	// Log.Error("HongHaoManager Test", "//////////CheckHongBaoTimeout now_time[%u] m_hongbao_timeout[%u] timeout[%u] m_mapHongBaoHistory[%u]", 
			// now_time, m_hongbao_timeout, timeout, m_mapHongBaoHistory.size());
	if (now_time - m_hongbao_timeout >= timeout)
	{
		
		m_hongbao_timeout = now_time;
	WGS_CHN_HONGBAO_INNER_LOCK
		std::map<uint32, GamePubData>::iterator mapi, endmapi = m_mapHongBaoHistory.end();
		for (mapi = m_mapHongBaoHistory.begin(); mapi != endmapi; ++ mapi)
		{
			GamePubData &gpd = mapi->second;
			uint32 create_time = sTools.GetDateTimeSeconds(gpd.create_time);
			// Log.Error("HongHaoManager Test", "//////////CheckHongBaoTimeout m_hongbao_timeout[%u] now_time[%u] create_time[%u]", 
				// m_hongbao_timeout, now_time, create_time);
			if (gpd.status == en_HongBaoStatus_Normal && now_time - create_time >= sXmlDataMgr.GetConfXMLValue("HONGBAO_TIMEOUT"))
			{
				gpd.status = en_HongBaoStatus_Timeout;
				Fields field;
				field["create_time"] = mapi->second.create_time;
				sPubDataMgr.UpdatePubData(mapi->second.pd_id, &field);
				uint32 coins = 0;
				std::list<HongBaoDetail> lstHBD;
				JsonToDetail(gpd.sdata1, &lstHBD);
				std::list<HongBaoDetail>::iterator iter, enditer = lstHBD.end();
				for (iter = lstHBD.begin(); iter != enditer; ++ iter)
				{
					HongBaoDetail &hbd = *iter;
					if (hbd.pid == 0)
					{
						coins += hbd.hbNum;
					}
				}
				// 发送信件
				const MailModel *pModel = sXmlDataMgr.GetMailModel("HONGBAO_MAIL");
				if (pModel)
				{
					char strContent[1024] = "";
					sprintf(strContent, pModel->szContent.c_str(), gpd.src_nick.c_str(), gpd.create_time.c_str(), gpd.pd_id, coins);
					sGLMgr.CreateCoinsMail(gpd.src_platform_id, pModel->szTitle, strContent, coins);					
				}
			}
			
		}
	}
	
}

//=============================游戏公共配置相关===========================

// 添加配置
bool GameCommonConfigManager::AddGameCommonConfig(stGameCommonConfig & gcc)
{
	Fields fields;
	sDataMgr.initData(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONCONFIG, &fields);
	
	fields["status"] = 1;
	fields["type"] = gcc.type;
	fields["sub_type"] = gcc.sub_type;
	fields["agent_id"] = gcc.agent_id;
	fields["game_id"] = gcc.game_id;
	fields["gz_id"] = gcc.gz_id;
	
	fields["data1"] = gcc.data1;
	fields["data2"] = gcc.data2;
	fields["data3"] = gcc.data3;
	fields["data4"] = gcc.data4;
	fields["data5"] = gcc.data5;
	fields["data6"] = gcc.data6;
	fields["data7"] = gcc.data7;
	fields["data8"] = gcc.data8;
	fields["data9"] = gcc.data9;
	fields["data10"] = gcc.data10;
	fields["data11"] = gcc.data11;
	fields["data12"] = gcc.data12;
	
	fields["fdata1"] = gcc.fdata1;
	fields["fdata2"] = gcc.fdata2;
	fields["fdata3"] = gcc.fdata3;
	fields["fdata4"] = gcc.fdata4;
	fields["fdata5"] = gcc.fdata5;
	fields["fdata6"] = gcc.fdata6;
	fields["fdata7"] = gcc.fdata7;
	fields["fdata8"] = gcc.fdata8;
	fields["fdata9"] = gcc.fdata9;
	fields["fdata10"] = gcc.fdata10;
	fields["fdata11"] = gcc.fdata11;
	fields["fdata12"] = gcc.fdata12;
	
	fields["sdata1"] = gcc.sdata1;
	fields["sdata2"] = gcc.sdata2;
	fields["sdata3"] = gcc.sdata3;
	fields["sdata4"] = gcc.sdata4;
	fields["sdata5"] = gcc.sdata5;
	fields["sdata6"] = gcc.sdata6;
	fields["sdata7"] = gcc.sdata7;
	fields["sdata8"] = gcc.sdata8;
	fields["sdata9"] = gcc.sdata9;
	fields["sdata10"] = gcc.sdata10;
	fields["sdata11"] = gcc.sdata11;
	fields["sdata12"] = gcc.sdata12;
	
	fields["create_time"] = gcc.create_time;
	fields["last_update_time"] = gcc.last_update_time;
	
	if (!sDataMgr.insertData(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONCONFIG, &fields))
		return false;
	
	gcc.config_id = fields["config_id"].GetUInt32();
	return true;
}

// 更新配置
bool GameCommonConfigManager::UpdateGameCommonConfig(const stGameCommonConfig & gcc)
{
	Fields fields;
	fields["config_id"] = gcc.config_id;
	fields["status"] = 1;
	fields["type"] = gcc.type;
	fields["sub_type"] = gcc.sub_type;
	fields["agent_id"] = gcc.agent_id;
	fields["game_id"] = gcc.game_id;
	fields["gz_id"] = gcc.gz_id;
	
	fields["data1"] = gcc.data1;
	fields["data2"] = gcc.data2;
	fields["data3"] = gcc.data3;
	fields["data4"] = gcc.data4;
	fields["data5"] = gcc.data5;
	fields["data6"] = gcc.data6;
	fields["data7"] = gcc.data7;
	fields["data8"] = gcc.data8;
	fields["data9"] = gcc.data9;
	fields["data10"] = gcc.data10;
	fields["data11"] = gcc.data11;
	fields["data12"] = gcc.data12;
	
	fields["fdata1"] = gcc.fdata1;
	fields["fdata2"] = gcc.fdata2;
	fields["fdata3"] = gcc.fdata3;
	fields["fdata4"] = gcc.fdata4;
	fields["fdata5"] = gcc.fdata5;
	fields["fdata6"] = gcc.fdata6;
	fields["fdata7"] = gcc.fdata7;
	fields["fdata8"] = gcc.fdata8;
	fields["fdata9"] = gcc.fdata9;
	fields["fdata10"] = gcc.fdata10;
	fields["fdata11"] = gcc.fdata11;
	fields["fdata12"] = gcc.fdata12;
	
	fields["sdata1"] = gcc.sdata1;
	fields["sdata2"] = gcc.sdata2;
	fields["sdata3"] = gcc.sdata3;
	fields["sdata4"] = gcc.sdata4;
	fields["sdata5"] = gcc.sdata5;
	fields["sdata6"] = gcc.sdata6;
	fields["sdata7"] = gcc.sdata7;
	fields["sdata8"] = gcc.sdata8;
	fields["sdata9"] = gcc.sdata9;
	fields["sdata10"] = gcc.sdata10;
	fields["sdata11"] = gcc.sdata11;
	fields["sdata12"] = gcc.sdata12;
	
	fields["create_time"] = gcc.create_time;
	fields["last_update_time"] = gcc.last_update_time;
	
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONCONFIG, &fields, "`config_id` = %u", gcc.config_id);
	return count > 0;
}

bool GameCommonConfigManager::UpdateGameCommonConfig(Fields * fields, const char * QueryString, ...)
{
	char sql[SQLBUFER_LEN] = ""; 
	va_list vlist; 
	va_start(vlist, QueryString); 
	vsnprintf(sql, SQLBUFER_LEN, QueryString, vlist); 
	va_end(vlist);
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONCONFIG, fields, sql);
	return count > 0;	
}

bool GameCommonConfigManager::UpdateGameCommonConfig(const uint32 & config_id, Fields * fields)
{
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONCONFIG, fields, "`config_id` = %u", config_id);
	return count > 0;	
}

// 获取配置
bool GameCommonConfigManager::GetGameCommonConfig(const uint32 & config_id, stGameCommonConfig * cc)
{
	assert (cc);
	FieldRows rows;
	sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONCONFIG, &rows, "`config_id` = %u", config_id);
	if (rows.empty())
		return false;
	
	Fields fields = rows.front();
	cc->config_id = fields["config_id"].GetUInt32();
	cc->status = fields["status"].GetUInt32();
	cc->type = fields["type"].GetUInt32();
	cc->sub_type = fields["sub_type"].GetUInt32();
	cc->agent_id = fields["agent_id"].GetUInt32();
	cc->game_id = fields["game_id"].GetUInt32();
	cc->gz_id = fields["gz_id"].GetUInt32();
	
	cc->data1 = fields["data1"].GetInt32();
	cc->data2 = fields["data2"].GetInt32();
	cc->data3 = fields["data3"].GetInt32();
	cc->data4 = fields["data4"].GetInt32();
	cc->data5 = fields["data5"].GetInt32();
	cc->data6 = fields["data6"].GetInt32();
	cc->data7 = fields["data7"].GetInt32();
	cc->data8 = fields["data8"].GetInt32();
	cc->data9 = fields["data9"].GetInt32();
	cc->data10 = fields["data10"].GetInt32();
	cc->data11 = fields["data11"].GetInt32();
	cc->data12 = fields["data12"].GetInt32();
	
	cc->fdata1 = fields["fdata1"].GetFloat();
	cc->fdata2 = fields["fdata2"].GetFloat();
	cc->fdata3 = fields["fdata3"].GetFloat();
	cc->fdata4 = fields["fdata4"].GetFloat();
	cc->fdata5 = fields["fdata5"].GetFloat();
	cc->fdata6 = fields["fdata6"].GetFloat();
	cc->fdata7 = fields["fdata7"].GetFloat();
	cc->fdata8 = fields["fdata8"].GetFloat();
	cc->fdata9 = fields["fdata9"].GetFloat();
	cc->fdata10 = fields["fdata10"].GetFloat();
	cc->fdata11 = fields["fdata11"].GetFloat();
	cc->fdata12 = fields["fdata12"].GetFloat();
	
	cc->sdata1 = fields["sdata1"].GetValue();
	cc->sdata2 = fields["sdata2"].GetValue();
	cc->sdata3 = fields["sdata3"].GetValue();
	cc->sdata4 = fields["sdata4"].GetValue();
	cc->sdata5 = fields["sdata5"].GetValue();
	cc->sdata6 = fields["sdata6"].GetValue();
	cc->sdata7 = fields["sdata7"].GetValue();
	cc->sdata8 = fields["sdata8"].GetValue();
	cc->sdata9 = fields["sdata9"].GetValue();
	cc->sdata10 = fields["sdata10"].GetValue();
	cc->sdata11 = fields["sdata11"].GetValue();
	cc->sdata12 = fields["sdata12"].GetValue();
	
	cc->create_time = fields["create_time"].GetValue();
	cc->last_update_time = fields["last_update_time"].GetValue();
	return true;
}

bool GameCommonConfigManager::GetGameCommonConfig(const uint32 & agent_id, const uint8 & type, stGameCommonConfig * cc)
{
	assert (cc);
	FieldRows rows;
	sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONCONFIG, &rows, "`status` < 255 AND `agent_id` = %u AND `type` = %u", agent_id, type);
	if (rows.empty())
		return false;
	
	Fields fields = rows.front();
	cc->config_id = fields["config_id"].GetUInt32();
	cc->status = fields["status"].GetUInt32();
	cc->type = fields["type"].GetUInt32();
	cc->sub_type = fields["sub_type"].GetUInt32();
	cc->agent_id = fields["agent_id"].GetUInt32();
	cc->game_id = fields["game_id"].GetUInt32();
	cc->gz_id = fields["gz_id"].GetUInt32();
	
	cc->data1 = fields["data1"].GetInt32();
	cc->data2 = fields["data2"].GetInt32();
	cc->data3 = fields["data3"].GetInt32();
	cc->data4 = fields["data4"].GetInt32();
	cc->data5 = fields["data5"].GetInt32();
	cc->data6 = fields["data6"].GetInt32();
	cc->data7 = fields["data7"].GetInt32();
	cc->data8 = fields["data8"].GetInt32();
	cc->data9 = fields["data9"].GetInt32();
	cc->data10 = fields["data10"].GetInt32();
	cc->data11 = fields["data11"].GetInt32();
	cc->data12 = fields["data12"].GetInt32();
	
	cc->fdata1 = fields["fdata1"].GetFloat();
	cc->fdata2 = fields["fdata2"].GetFloat();
	cc->fdata3 = fields["fdata3"].GetFloat();
	cc->fdata4 = fields["fdata4"].GetFloat();
	cc->fdata5 = fields["fdata5"].GetFloat();
	cc->fdata6 = fields["fdata6"].GetFloat();
	cc->fdata7 = fields["fdata7"].GetFloat();
	cc->fdata8 = fields["fdata8"].GetFloat();
	cc->fdata9 = fields["fdata9"].GetFloat();
	cc->fdata10 = fields["fdata10"].GetFloat();
	cc->fdata11 = fields["fdata11"].GetFloat();
	cc->fdata12 = fields["fdata12"].GetFloat();
	
	cc->sdata1 = fields["sdata1"].GetValue();
	cc->sdata2 = fields["sdata2"].GetValue();
	cc->sdata3 = fields["sdata3"].GetValue();
	cc->sdata4 = fields["sdata4"].GetValue();
	cc->sdata5 = fields["sdata5"].GetValue();
	cc->sdata6 = fields["sdata6"].GetValue();
	cc->sdata7 = fields["sdata7"].GetValue();
	cc->sdata8 = fields["sdata8"].GetValue();
	cc->sdata9 = fields["sdata9"].GetValue();
	cc->sdata10 = fields["sdata10"].GetValue();
	cc->sdata11 = fields["sdata11"].GetValue();
	cc->sdata12 = fields["sdata12"].GetValue();
	
	cc->create_time = fields["create_time"].GetValue();
	cc->last_update_time = fields["last_update_time"].GetValue();
	return true;
}

// 获取配置列表
uint32 GameCommonConfigManager::GetGameCommonConfigList(std::list<stGameCommonConfig> * lstData, const char * query,...)
{
	va_list argp;
	va_start(argp, query);
	lstData->clear();
	FieldRows fieldRows;
	
	char sql[SQLBUFER_LEN] = "";
	va_list vlist;
	va_start(vlist, query);
	vsnprintf(sql, SQLBUFER_LEN, query, vlist); 
	va_end(vlist);
	
	if (!sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONCONFIG, &fieldRows, sql))
		return 0;
	
	FieldRows::iterator iter, enditer = fieldRows.end();
	for (iter = fieldRows.begin(); iter != enditer; ++ iter)
	{
		stGameCommonConfig gcc;
		Fields &fields = *iter;
		gcc.config_id = fields["config_id"].GetUInt32();
		gcc.status = fields["status"].GetUInt32();
		gcc.type = fields["type"].GetUInt32();
		gcc.sub_type = fields["sub_type"].GetUInt32();
		gcc.agent_id = fields["agent_id"].GetUInt32();
		gcc.game_id = fields["game_id"].GetUInt32();
		gcc.gz_id = fields["gz_id"].GetUInt32();
		
		gcc.data1 = fields["data1"].GetInt32();
		gcc.data2 = fields["data2"].GetInt32();
		gcc.data3 = fields["data3"].GetInt32();
		gcc.data4 = fields["data4"].GetInt32();
		gcc.data5 = fields["data5"].GetInt32();
		gcc.data6 = fields["data6"].GetInt32();
		gcc.data7 = fields["data7"].GetInt32();
		gcc.data8 = fields["data8"].GetInt32();
		gcc.data9 = fields["data9"].GetInt32();
		gcc.data10 = fields["data10"].GetInt32();
		gcc.data11 = fields["data11"].GetInt32();
		gcc.data12 = fields["data12"].GetInt32();
		
		gcc.fdata1 = fields["fdata1"].GetFloat();
		gcc.fdata2 = fields["fdata2"].GetFloat();
		gcc.fdata3 = fields["fdata3"].GetFloat();
		gcc.fdata4 = fields["fdata4"].GetFloat();
		gcc.fdata5 = fields["fdata5"].GetFloat();
		gcc.fdata6 = fields["fdata6"].GetFloat();
		gcc.fdata7 = fields["fdata7"].GetFloat();
		gcc.fdata8 = fields["fdata8"].GetFloat();
		gcc.fdata9 = fields["fdata9"].GetFloat();
		gcc.fdata10 = fields["fdata10"].GetFloat();
		gcc.fdata11 = fields["fdata11"].GetFloat();
		gcc.fdata12 = fields["fdata12"].GetFloat();
		
		gcc.sdata1 = fields["sdata1"].GetValue();
		gcc.sdata2 = fields["sdata2"].GetValue();
		gcc.sdata3 = fields["sdata3"].GetValue();
		gcc.sdata4 = fields["sdata4"].GetValue();
		gcc.sdata5 = fields["sdata5"].GetValue();
		gcc.sdata6 = fields["sdata6"].GetValue();
		gcc.sdata7 = fields["sdata7"].GetValue();
		gcc.sdata8 = fields["sdata8"].GetValue();
		gcc.sdata9 = fields["sdata9"].GetValue();
		gcc.sdata10 = fields["sdata10"].GetValue();
		gcc.sdata11 = fields["sdata11"].GetValue();
		gcc.sdata12 = fields["sdata12"].GetValue();
		
		gcc.create_time = fields["create_time"].GetValue();
		gcc.last_update_time = fields["last_update_time"].GetValue();
		lstData->push_back(gcc);
	}
	
	return lstData->size();
}

GameCommonConfigManager::GameCommonConfigManager()
{
	LoadAllConfig();
}

// 启动服务器的时候初始所有配置
void GameCommonConfigManager::LoadAllConfig()
{
	m_mapCommonTurnTable.clear();
	m_mapCommonCountLogin.clear();
	m_mapCommonRelief.clear();
	m_mapActivityValue.clear();
	
	std::list<stGameCommonConfig> lstData;
	if(!GetGameCommonConfigList(&lstData, " `status` < 255 "))
		return ;
	
	std::list<stGameCommonConfig>::iterator iter, ei = lstData.end();
	for(iter = lstData.begin(); iter!=ei; ++iter)
	{
		switch((*iter).type)
		{
		case enGameCommonConfigType_TurnTable:	// 转盘
			UpdateTurnTableConfig(*iter);
			break;
		case enGameCommonConfigType_CountLogin:	// 累计登录
			UpdateCountLoginConfig(*iter);
			break;
		case enGameCommonConfigType_Relief:		// 救济礼包
			UpdateReliefConfig(*iter);
			break;
		case enGameCommonConfigType_ActivityValue:	// 活跃值
			UpdateActivityValueConfig(*iter);
			break;
		case enGameCommonConfigType_CommonMission:	// 任务配置
			UpdateMissionConfig(*iter);
			break;
		case enGameCommonConfigType_FuDai:			// 福袋配置
			UpdateFuDaiConfig(*iter);
			break;
		default:
			break;
		}
	}	
}

// 网关请求URL操作配置
uint8 GameCommonConfigManager::GatewayOperatorCommonConfig(String & opName, String & strParams, String & strReturnData)
{
WGS_CONFIG_LOCK
	if(!opName.compare("turntable"))
	{// 转盘配置
		return GatewayOperatorTurnTableConfig(strParams, strReturnData);
	}
	else if(!opName.compare("countlogin"))
	{// 累计登录配置
		return GatewayOperatorCountLoginConfig(strParams, strReturnData);
	}
	else if(!opName.compare("relief"))
	{// 救济礼包配置
		return GatewayOperatorReliefConfig(strParams, strReturnData);
	}
	else if(!opName.compare("activityvalue"))
	{// 活跃值配置
		return GatewayOperatorActivityValueConfig(strParams, strReturnData);
	}
	else if(!opName.compare("commonmission"))
	{// 任务配置
		return GatewayOperatorMissionConfig(strParams, strReturnData);
	}
	else if(!opName.compare("fudai"))
	{// 福袋配置
		return GatewayOperatorFuDaiConfig(strParams, strReturnData);
	}
	
	return 0;
}

// 网关操作转盘配置
uint8 GameCommonConfigManager::GatewayOperatorTurnTableConfig(String & strParams, String & strReturnData)
{
	Json::Value valParams;
	Json::Reader reader;
	
	reader.parse(strParams, valParams);
	if(valParams.empty())
		return 2;
	
	// 参数不对
	if(!valParams.isMember("op_type") || !valParams.isMember("agent_id"))
		return 3;
	
	stGameCommonConfig cc;
	uint8 type = enGameCommonConfigType_TurnTable;
	uint32 agent_id = 0;
	if(valParams["agent_id"].isString())
		agent_id = StringConverter::parseUnsignedInt(valParams["agent_id"].asString());
	else
		agent_id = valParams["agent_id"].asUInt();
	
	if(!GetGameCommonConfig(agent_id, type, &cc))
		return 4;
	
	Json::Value valDataList;
	Json::FastWriter w;
	
	uint8 op_type = valParams["op_type"].asUInt();
	if(op_type == 1)
	{// 读取数据
		strReturnData = cc.sdata1;
		return 1;
	}
	else if(op_type == 2)
	{// 修改数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("index"))
				return 7;
			
			if(!valData.isMember("model_id") && !valData.isMember("num") && !valData.isMember("percent") && !valData.isMember("img_url"))
				return 8;
			
			uint32 total_percent = 0;
			bool bChangeData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["index"].asUInt() == (*iterVal)["index"].asUInt())
				{
					if(valData.isMember("model_id"))
						(*iterVal)["model_id"] = valData["model_id"];
					
					if(valData.isMember("num"))
						(*iterVal)["num"] = valData["num"];
					
					if(valData.isMember("percent"))
						(*iterVal)["percent"] = valData["percent"].asUInt();
					
					if(valData.isMember("img_url"))
						(*iterVal)["img_url"] = valData["img_url"];
					
					bChangeData = true;
				}
				
				total_percent += (*iterVal)["percent"].asUInt();
			}
			
			// 配置几率总和不是100%
			// if(total_percent != 100000)
				// return 14;
			
			if(bChangeData)
			{
				cc.sdata1 = w.write(valDataList);
				UpdateGameCommonConfig(cc);
				return 1;
			}
			else
			{
				return 12;
			}
		}
		catch (exception& e) 
		{
			return 11;
		} 
	}
	else if(op_type == 3)
	{//  新增数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("model_id") && !valData.isMember("num") && !valData.isMember("percent"))
				return 8;
			
			reader.parse(cc.sdata1, valDataList);
			
			Json::Value valNew;
			valNew["index"] = valDataList.size() + 1;
			valNew["model_id"] = valData["model_id"];
			valNew["num"] = valData["num"];
			valNew["percent"] = valData["percent"].asUInt();
			if(valData.isMember("img_url"))
				valNew["img_url"] = valData["img_url"];
			
			valDataList.append(valNew);
			
			cc.sdata1 = w.write(valDataList);
			UpdateGameCommonConfig(cc);
			return 1;
		}
		catch (exception& e) 
		{ 
			return 11;
		} 
	}
	else if(op_type == 4)
	{// 删除数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("index"))
				return 7;
			
			Json::Value valNew;
			
			uint8 index = 0;
			bool bChangeData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["index"].asUInt() == (*iterVal)["index"].asUInt())
				{
					bChangeData = true;
					continue;
				}
				
				(*iterVal)["index"] = index + 1;
				valNew[index++] = *iterVal;
			}
			
			if(bChangeData)
			{
				if(valNew.empty())
					cc.sdata1 = "";
				else
					cc.sdata1 = w.write(valNew);
				
				UpdateGameCommonConfig(cc);
				return 1;
			}
			else
			{
				return 12;
			}
		}
		catch (exception& e) 
		{ 
			return 11;
		} 
	}
	
	return 0;
}

// 网关操作累计登录配置
uint8 GameCommonConfigManager::GatewayOperatorCountLoginConfig(String & strParams, String & strReturnData)
{
	Json::Value valParams;
	Json::Reader reader;
	
	reader.parse(strParams, valParams);
	if(valParams.empty())
		return 2;
	
	// 参数不对
	if(!valParams.isMember("op_type") || !valParams.isMember("agent_id"))
		return 3;
	
	stGameCommonConfig cc;
	uint8 type = enGameCommonConfigType_CountLogin;
	uint32 agent_id = 0;
	if(valParams["agent_id"].isString())
		agent_id = StringConverter::parseUnsignedInt(valParams["agent_id"].asString());
	else
		agent_id = valParams["agent_id"].asUInt();
	
	if(!GetGameCommonConfig(agent_id, type, &cc))
		return 4;
	
	Json::Value valDataList;
	Json::FastWriter w;
	
	uint8 op_type = valParams["op_type"].asUInt();
	if(op_type == 1)
	{// 读取数据
		strReturnData = cc.sdata1;
		return 1;
	}
	else if(op_type == 2)
	{// 修改数据
		
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("index"))
				return 7;
			
			if(!valData.isMember("model_id") && !valData.isMember("num") && !valData.isMember("days") && !valData.isMember("img_url"))
				return 8;
			
			bool bChangeData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["index"].asUInt() == (*iterVal)["index"].asUInt())
				{
					if(valData.isMember("model_id"))
						(*iterVal)["model_id"] = valData["model_id"];
					
					if(valData.isMember("num"))
						(*iterVal)["num"] = valData["num"];
					
					if(valData.isMember("days"))
						(*iterVal)["days"] = valData["days"];
					
					if(valData.isMember("img_url"))
						(*iterVal)["img_url"] = valData["img_url"];
					
					bChangeData = true;
					break;
				}
			}
			
			if(bChangeData)
			{
				cc.sdata1 = w.write(valDataList);
				UpdateGameCommonConfig(cc);
				return 1;
			}
			else
			{
				return 12;
			}
		}
		catch (exception& e) 
		{ 
			return 11;
		} 
	}
	else if(op_type == 3)
	{//  新增数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("model_id") && !valData.isMember("num") && !valData.isMember("days"))
				return 8;
			
			bool bUpdateData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["days"].asUInt() == (*iterVal)["days"].asUInt())
				{
					(*iterVal)["model_id"] = valData["model_id"];
					(*iterVal)["num"] = valData["num"];
					if(valData.isMember("img_url"))
						(*iterVal)["img_url"] = valData["img_url"];
					
					bUpdateData = true;
					break;
				}
			}
			
			if(!bUpdateData)
			{
				Json::Value valNew;
				valNew["index"] = valDataList.size() + 1;
				valNew["model_id"] = valData["model_id"];
				valNew["num"] = valData["num"];
				valNew["days"] = valData["days"];
				if(valData.isMember("img_url"))
					valNew["img_url"] = valData["img_url"];
				
				valDataList.append(valNew);
			}
			
			cc.sdata1 = w.write(valDataList);
			UpdateGameCommonConfig(cc);
			return 1;
		}
		catch (exception& e) 
		{ 
			return 11;
		}
	}
	else if(op_type == 4)
	{// 删除数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("index"))
				return 7;
			
			Json::Value valNew;
			
			uint8 index = 0;
			bool bChangeData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["index"].asUInt() == (*iterVal)["index"].asUInt())
				{
					bChangeData = true;
					continue;
				}
				
				(*iterVal)["index"] = index+1;
				valNew[index++] = *iterVal;
			}
			
			if(bChangeData)
			{
				if(valNew.empty())
					cc.sdata1 = "";
				else
					cc.sdata1 = w.write(valNew);
				
				UpdateGameCommonConfig(cc);
				return 1;
			}
			else
			{
				return 12;
			}
		}
		catch (exception& e) 
		{ 
			return 11;
		}
	}
	
	return 0;
}

// 网关操作救济礼包配置
uint8 GameCommonConfigManager::GatewayOperatorReliefConfig(String & strParams, String & strReturnData)
{
	Json::Value valParams;
	Json::Reader reader;
	
	reader.parse(strParams, valParams);
	if(valParams.empty())
		return 2;
	
	// 参数不对
	if(!valParams.isMember("op_type") || !valParams.isMember("agent_id"))
		return 3;
	
	stGameCommonConfig cc;
	uint8 type = enGameCommonConfigType_Relief;
	uint32 agent_id = 0;
	if(valParams["agent_id"].isString())
		agent_id = StringConverter::parseUnsignedInt(valParams["agent_id"].asString());
	else
		agent_id = valParams["agent_id"].asUInt();
	
	Json::Value valReturn;
	
	uint8 op_type = valParams["op_type"].asUInt();
	if(!GetGameCommonConfig(agent_id, type, &cc) && op_type != 3)
		return 4;
	
	if(op_type == 1)
	{// 读取数据
		valReturn["model_id"] = cc.data1;
		valReturn["num"] = cc.data2;
		valReturn["limit_coins"] = cc.data3;
		valReturn["max_count"] = cc.data4;
		valReturn["type"] = cc.data5;
		valReturn["index"] = 1;
	}
	else if(op_type == 2)
	{// 修改数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			valReturn = valParams["data"];
			
			// 无参数修改
			if(!valReturn.isMember("model_id") && !valReturn.isMember("num") && !valReturn.isMember("limit_coins") && 
				!valReturn.isMember("max_count") && !valReturn.isMember("type"))
				return 6;
			
			if(valReturn.isMember("model_id"))
				cc.data1 = valReturn["model_id"].asInt();
			
			if(valReturn.isMember("num"))
				cc.data2 = valReturn["num"].asInt();
			
			if(valReturn.isMember("limit_coins"))
				cc.data3 = valReturn["limit_coins"].asInt();
			
			if(valReturn.isMember("max_count"))
				cc.data4 = valReturn["max_count"].asInt();
			
			if(valReturn.isMember("type"))
				cc.data5 = valReturn["type"].asInt();
			
			UpdateGameCommonConfig(cc);
		}
		catch (exception& e) 
		{ 
			return 11;
		}
	}
	else if(op_type == 3)
	{// 添加数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			valReturn = valParams["data"];
			
			// 无参数修改
			if(!valReturn.isMember("model_id") && 
				!valReturn.isMember("num") && 
				!valReturn.isMember("limit_coins") && 
				!valReturn.isMember("max_count") && 
				!valReturn.isMember("type"))
				return 6;
			
			cc.data1 = valReturn["model_id"].asUInt();
			cc.data2 = valReturn["num"].asUInt();
			cc.data3 = valReturn["limit_coins"].asUInt();
			cc.data4 = valReturn["max_count"].asUInt();
			cc.data5 = valReturn["type"].asUInt();
			
			if(cc.config_id == 0)
			{// 没有数据，添加
				cc.status = 1;
				cc.agent_id = agent_id;
				AddGameCommonConfig(cc);
			}
			else
			{// 已有数据，更新
				UpdateGameCommonConfig(cc);
			}
		}
		catch (exception& e) 
		{ 
			return 11;
		}
	}
	else if(op_type == 4)
	{// 删除数据
		return 0;
	}
	
	if(op_type == 1)
	{// 查询，返回结果
		Json::FastWriter w;
		strReturnData = w.write(valReturn);
	}
	
	return 1;
}

// 网关操作活跃值配置
uint8 GameCommonConfigManager::GatewayOperatorActivityValueConfig(String & strParams, String & strReturnData)
{
	Json::Value valParams;
	Json::Reader reader;
	
	reader.parse(strParams, valParams);
	if(valParams.empty())
		return 2;
	
	// 参数不对
	if(!valParams.isMember("op_type") || !valParams.isMember("agent_id"))
		return 3;
	
	stGameCommonConfig cc;
	uint8 type = enGameCommonConfigType_ActivityValue;
	uint32 agent_id = 0;
	if(valParams["agent_id"].isString())
		agent_id = StringConverter::parseUnsignedInt(valParams["agent_id"].asString());
	else
		agent_id = valParams["agent_id"].asUInt();
	
	if(!GetGameCommonConfig(agent_id, type, &cc))
		return 4;
	
	Json::Value valDataList;
	Json::FastWriter w;
	
	uint8 op_type = valParams["op_type"].asUInt();
	if(op_type == 1)
	{// 读取数据
		strReturnData = cc.sdata1;
		return 1;
	}
	else if(op_type == 2)
	{// 修改数据
		
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("index"))
				return 7;
			
			if(!valData.isMember("type") && !valData.isMember("count") && !valData.isMember("value"))
				return 8;
			
			bool bChangeData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["index"].asUInt() == (*iterVal)["index"].asUInt())
				{
					if(valData.isMember("type"))
						(*iterVal)["type"] = valData["type"];
					
					if(valData.isMember("count"))
						(*iterVal)["count"] = valData["count"];
					
					if(valData.isMember("value"))
						(*iterVal)["value"] = valData["value"];
					
					(*iterVal)["desc"] = GetActivityDescString(cc.sdata2, (*iterVal)["type"].asUInt(), (*iterVal)["count"].asUInt(), (*iterVal)["value"].asUInt());
					bChangeData = true;
					break;
				}
			}
			
			if(bChangeData)
			{
				cc.sdata1 = w.write(valDataList);
				UpdateGameCommonConfig(cc);
				return 1;
			}
			else
			{
				return 12;
			}
		}
		catch (exception& e) 
		{ 
			return 11;
		} 
	}
	else if(op_type == 3)
	{//  新增数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("type") && !valData.isMember("count") && !valData.isMember("value"))
				return 8;
			
			bool bUpdateData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["type"].asUInt() == (*iterVal)["type"].asUInt())
				{
					(*iterVal)["count"] = valData["count"];
					(*iterVal)["value"] = valData["value"];
					(*iterVal)["desc"] = GetActivityDescString(cc.sdata2, (*iterVal)["type"].asUInt(), (*iterVal)["count"].asUInt(), (*iterVal)["value"].asUInt());
					
					bUpdateData = true;
					break;
				}
			}
			
			if(!bUpdateData)
			{
				Json::Value valNew;
				valNew["index"] = valDataList.size() + 1;
				valNew["type"] = valData["type"];
				valNew["count"] = valData["count"];
				valNew["value"] = valData["value"];
				valNew["desc"] = GetActivityDescString(cc.sdata2,valData["type"].asUInt(), valData["count"].asUInt(), valData["value"].asUInt());
				
				valDataList.append(valNew);
			}
			
			cc.sdata1 = w.write(valDataList);
			UpdateGameCommonConfig(cc);
			return 1;
		}
		catch (exception& e) 
		{ 
			return 11;
		}
	}
	else if(op_type == 4)
	{// 删除数据
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("index"))
				return 7;
			
			Json::Value valNew;
			
			uint8 index = 0;
			bool bChangeData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["index"].asUInt() == (*iterVal)["index"].asUInt())
				{
					bChangeData = true;
					continue;
				}
				
				(*iterVal)["index"] = index+1;
				valNew[index++] = *iterVal;
			}
			
			if(bChangeData)
			{
				if(valNew.empty())
					cc.sdata1 = "";
				else
					cc.sdata1 = w.write(valNew);
				
				UpdateGameCommonConfig(cc);
				return 1;
			}
			else
			{
				return 12;
			}
		}
		catch (exception& e) 
		{ 
			return 11;
		}
	}
	
	return 0;
}

// 网关操作任务配置
uint8 GameCommonConfigManager::GatewayOperatorMissionConfig(String & strParams, String & strReturnData)
{
	Json::Value valParams;
	Json::Reader reader;
	
	reader.parse(strParams, valParams);
	if(valParams.empty())
		return 2;
	
	// 参数不对
	if(!valParams.isMember("op_type") || !valParams.isMember("agent_id"))
		return 3;
	
	stGameCommonConfig cc;
	uint8 type = enGameCommonConfigType_CommonMission;
	uint32 agent_id = 0;
	if(valParams["agent_id"].isString())
		agent_id = StringConverter::parseUnsignedInt(valParams["agent_id"].asString());
	else
		agent_id = valParams["agent_id"].asUInt();
	
	if(!GetGameCommonConfig(agent_id, type, &cc))
		return 4;
	
	Json::Value valDataList;
	Json::FastWriter w;
	
	uint8 op_type = valParams["op_type"].asUInt();
	if(op_type == 1)
	{// 读取数据
		strReturnData = cc.sdata1;
		return 1;
	}
	else if(op_type == 2)
	{// 修改数据
		
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("type"))
				return 13;
			
			if(!valData.isMember("index") && !valData.isMember("name") && !valData.isMember("content") && !valData.isMember("items"))
				return 8;
			
			bool bChangeData = false;
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["type"].asUInt() == (*iterVal)["type"].asUInt())
				{
					if(valData.isMember("index"))
					{// 改任务列表中的任务数据
						if((*iterVal).isMember("missions"))
						{
							for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
							{
								if((*iterMissions)["index"].asUInt() == valData["index"].asUInt())
								{
									if(valData.isMember("name"))
										(*iterMissions)["name"] = valData["name"];
									
									if(valData.isMember("content"))
										(*iterMissions)["content"] = valData["content"];
									
									if(valData.isMember("items"))
										(*iterMissions)["items"] = valData["items"];
									
									bChangeData = true;
									break;
								}
							}
							
							if(bChangeData)
								break;
						}
					}
					else
					{// 改整个列表的数据
						if(valData.isMember("items"))
						{// 修改奖励列表数据
							(*iterVal)["items"] = valData["items"];
							bChangeData = true;
							break;
						}
					}
					
					(*iterVal)["desc"] = GetActivityDescString(cc.sdata2, (*iterVal)["type"].asUInt(), (*iterVal)["count"].asUInt(), (*iterVal)["value"].asUInt());
					bChangeData = true;
					break;
				}
			}
			
			if(bChangeData)
			{
				cc.sdata1 = w.write(valDataList);
				UpdateGameCommonConfig(cc);
				return 1;
			}
			else
			{
				return 12;
			}
		}
		catch (exception& e) 
		{ 
			return 11;
		} 
	}
	else if(op_type == 3)
	{//  新增数据
		
	}
	else if(op_type == 4)
	{// 删除数据
		
	}
	
	return 0;
}

// 网关操作福袋配置
uint8 GameCommonConfigManager::GatewayOperatorFuDaiConfig(String & strParams, String & strReturnData)
{
	Json::Value valParams;
	Json::Reader reader;
	
	reader.parse(strParams, valParams);
	if(valParams.empty())
		return 2;
	
	// 参数不对
	if(!valParams.isMember("op_type") || !valParams.isMember("agent_id"))
		return 3;
	
	stGameCommonConfig cc;
	uint8 type = enGameCommonConfigType_FuDai;
	uint32 agent_id = 0;
	if(valParams["agent_id"].isString())
		agent_id = StringConverter::parseUnsignedInt(valParams["agent_id"].asString());
	else
		agent_id = valParams["agent_id"].asUInt();
	
	if(!GetGameCommonConfig(agent_id, type, &cc))
		return 4;
	
	Json::Value valDataList;
	Json::FastWriter w;
	
	uint8 op_type = valParams["op_type"].asUInt();
	if(op_type == 1)
	{// 读取数据
		strReturnData = cc.sdata1;
		return 1;
	}
	else if(op_type == 2)
	{// 修改数据
		
		try
		{
			if(!valParams.isMember("data"))
				return 5;
			
			Json::Value valData = valParams["data"];
			if(!valData.isMember("index"))
				return 7;
			
			if(!valData.isMember("items") && !valData.isMember("percent"))
				return 8;
			
			bool bChangeData = false;
			uint32 total_percent = 0;
			
			reader.parse(cc.sdata1, valDataList);
			for (Json::Value::iterator iterVal=valDataList.begin(); iterVal!=valDataList.end(); ++iterVal)
			{
				if(valData["index"].asUInt() == (*iterVal)["index"].asUInt())
				{
					if(valData.isMember("items"))
						(*iterVal)["items"] = valData["items"];
					
					if(valData.isMember("percent"))
					{
						(*iterVal)["percent"] = valData["percent"].asUInt();
					}
					
					bChangeData = true;
				}
				
				total_percent += (*iterVal)["percent"].asUInt();
			}
			
			// 配置几率总和不是100%
			// if(total_percent != 100000)
				// return 14;
			
			if(bChangeData)
			{
				cc.sdata1 = w.write(valDataList);
				UpdateGameCommonConfig(cc);
				return 1;
			}
			else
			{
				return 12;
			}
		}
		catch (exception& e) 
		{ 
			return 11;
		} 
	}
	else if(op_type == 3)
	{//  新增数据
		
	}
	else if(op_type == 4)
	{// 删除数据
		
	}
	
	return 0;
}

// 登录转盘配置
void GameCommonConfigManager::UpdateTurnTableConfig(stGameCommonConfig stGCC)
{
	Json::Value val;
	Json::Reader reader;
	reader.parse(stGCC.sdata1, val);
	
	if(val.empty())
		return ;
	
	std::vector<stCommonTurnTable> vCTT;
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		stCommonTurnTable stCTT;
		stCTT.type = stGCC.data1;
		stCTT.index = (*iterVal)["index"].asUInt();
		stCTT.model_id = (*iterVal)["model_id"].asUInt();
		stCTT.num = (*iterVal)["num"].asUInt();
		
		stCTT.percent = (*iterVal)["percent"].asUInt();
		stCTT.img_url = (*iterVal)["img_url"].asString();
		
		Log.Debug("GameCommonConfigManager::UpdateTurnTableConfig","type[%u] index[%u] model_id[%u]", stCTT.type, stCTT.index, stCTT.model_id);
		vCTT.push_back(stCTT);
	}
	
	std::map<uint32, std::vector<stCommonTurnTable> >::iterator fit = m_mapCommonTurnTable.find(stGCC.agent_id);
	if(fit == m_mapCommonTurnTable.end())
	{// 没有就添加
		m_mapCommonTurnTable.insert(std::make_pair(stGCC.agent_id, vCTT));
	}
	else
	{// 有数据就更新
		fit->second = vCTT;
	}
}

// 累计登录奖励配置
void GameCommonConfigManager::UpdateCountLoginConfig(stGameCommonConfig stGCC)
{
	Json::Value val;
	Json::Reader reader;
	reader.parse(stGCC.sdata1, val);
	
	if(val.empty())
		return ;
	
	std::vector<stCommonCountLogin> vCCL;
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		stCommonCountLogin stCCL;
		stCCL.index = (*iterVal)["index"].asUInt();
		stCCL.days = (*iterVal)["days"].asUInt();
		stCCL.model_id = (*iterVal)["model_id"].asUInt();
		stCCL.num = (*iterVal)["num"].asUInt();
		stCCL.img_url = (*iterVal)["img_url"].asString();
		
		Log.Debug("GameCommonConfigManager::UpdateCountLoginConfig","index[%u] model_id[%u] days[%u]", stCCL.index, stCCL.model_id, stCCL.days);
		vCCL.push_back(stCCL);
	}
	
	std::map<uint32, std::vector<stCommonCountLogin> >::iterator fit = m_mapCommonCountLogin.find(stGCC.agent_id);
	if(fit == m_mapCommonCountLogin.end())
	{// 没有就添加
		m_mapCommonCountLogin.insert(std::make_pair(stGCC.agent_id, vCCL));
	}
	else
	{// 有数据就更新
		fit->second = vCCL;
	}
}

// 救济礼包相关
void GameCommonConfigManager::UpdateReliefConfig(stGameCommonConfig stGCC)
{
	stCommonRelief stCR;
	stCR.agent_id = stGCC.agent_id;
	stCR.model_id = stGCC.data1;
	stCR.num = stGCC.data2;
	stCR.limit_coins = stGCC.data3;
	stCR.max_count = stGCC.data4;
	stCR.type = stGCC.data5;
	
	Log.Debug("GameCommonConfigManager::UpdateReliefConfig","agent_id[%u] model_id[%u] max_count[%u]", stCR.agent_id, stCR.model_id, stCR.max_count);
	std::map<uint32, stCommonRelief>::iterator fit = m_mapCommonRelief.find(stGCC.agent_id);
	if(fit == m_mapCommonRelief.end())
	{// 没有就添加
		m_mapCommonRelief.insert(std::make_pair(stCR.agent_id, stCR));
	}
	else
	{// 有数据就更新
		fit->second = stCR;
	}
}

// 活跃值配置
void GameCommonConfigManager::UpdateActivityValueConfig(stGameCommonConfig stGCC)
{
	Json::Value val;
	Json::Reader reader;
	reader.parse(stGCC.sdata1, val);
	
	if(val.empty())
		return ;
	
	std::vector<stCommonActivityValue> vCAV;
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		stCommonActivityValue stCAV;
		stCAV.agent_id = stGCC.agent_id;
		stCAV.index = (*iterVal)["index"].asUInt();
		stCAV.type = (*iterVal)["type"].asUInt();
		stCAV.count = (*iterVal)["count"].asUInt();
		stCAV.activity_value = (*iterVal)["value"].asUInt();
		
		Log.Debug("GameCommonConfigManager::UpdateActivityValueConfig","type[%u] count[%u] activity_value[%u]", stCAV.type, stCAV.count, stCAV.activity_value);
		vCAV.push_back(stCAV);
	}
	
	std::map<uint32, std::vector<stCommonActivityValue> >::iterator fit = m_mapActivityValue.find(stGCC.agent_id);
	if(fit == m_mapActivityValue.end())
	{// 没有就添加
		m_mapActivityValue.insert(std::make_pair(stGCC.agent_id, vCAV));
	}
	else
	{// 有数据就更新
		fit->second = vCAV;
	}
}

// 增加活跃值
bool GameCommonConfigManager::AddActivityValue(CharPtr & pChr, const uint32 & type, const uint32 & count)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	AICreatureBaseInterface * pChrAiInfe = TO_CREATURE_BASE_INTERFACE(pChr->getAIInterface());
	if(!pChrAiInfe)
		return false;
	
WGS_CONFIG_LOCK
	uint32 agent_id = pUser->getUInt32Field("reg_from");
	std::map<uint32, std::vector<stCommonActivityValue> >::iterator fit = m_mapActivityValue.find(agent_id);
	if(fit == m_mapActivityValue.end())
		return false;
	
	std::vector<stCommonActivityValue>::iterator iter, ei = fit->second.end();
	for(iter = fit->second.begin(); iter!=ei; ++iter)
	{
		Log.Debug("GameCommonConfigManager::AddActivityValue","type[%u:%u], count[%u:%u]", (*iter).type, type, (*iter).count, count);
		if((*iter).type == type && (*iter).count >= count)
		{// 调用URL
			switch(type)
			{
			case enActivityValueGetType_Login:
				if(pChrAiInfe->GetXMLData("DAY_DLCS_OVER") > 0)
					return false;
				
				break;
			case enActivityValueGetType_GmaeCount:
				if(pChrAiInfe->GetXMLData("DAY_YXJS_OVER") > 0)
					return false;
				
				break;
			case enActivityValueGetType_JoinMatch:
				if(pChrAiInfe->GetXMLData("DAY_CYBS_OVER") > 0)
					return false;
				
				break;
			case enActivityValueGetType_TotalWinCount:
				if(pChrAiInfe->GetXMLData("DAY_LJSL_OVER") > 0)
					return false;
				
				break;
			case enActivityValueGetType_TtoalWinCoins:
				if(pChrAiInfe->GetXMLData("DAY_LJYQ_OVER") > 0)
					return false;
				
				break;
			default:
				break;
			}
			
			String strTitle = /* sXmlDataMgr.GetGatewayHttpHostAddr(agent_id) */"http://open.dev.8z.net:10001";
			strTitle += "/platform/addactivityvalue";
			
			// pid
			uint32 pid = pUser->getUInt32Field("platform_id");
			String strUrl = "pid=";
			strUrl += StringConverter::toString(pid);
			
			// type
			strUrl += "&type=";
			strUrl += StringConverter::toString(type);
			
			// value
			uint32 value = pUser->getUInt32Field("platform_id");
			strUrl += "&value=";
			strUrl += StringConverter::toString(value);
			
			// 签名
			CMD5 md5;
			strUrl += "&sig=";
			strUrl += md5.GenerateMD5(StringConverter::toString(pid) + StringConverter::toString(type) + StringConverter::toString(value) + SERVERINFO_URL_SECRET);
			
			Log.Debug("GameCommonConfigManager::AddActivityValue","strTitle[%s]", strTitle.c_str());
			String recv_result = httpd_request(strTitle, REQUIRE_URL_TIMEOUT, "POST", strUrl.c_str());
			Log.Debug("GameCommonConfigManager::AddActivityValue","recv_result[%s]", recv_result.c_str());
			
			switch(type)
			{
			case enActivityValueGetType_Login:
				pChrAiInfe->SetXMLData("DAY_DLCS_OVER",1);
				break;
			case enActivityValueGetType_GmaeCount:
				pChrAiInfe->SetXMLData("DAY_YXJS_OVER",1);
				break;
			case enActivityValueGetType_JoinMatch:
				pChrAiInfe->SetXMLData("DAY_CYBS_OVER",1);
				break;
			case enActivityValueGetType_TotalWinCount:
				pChrAiInfe->SetXMLData("DAY_LJSL_OVER",1);
				break;
			case enActivityValueGetType_TtoalWinCoins:
				pChrAiInfe->SetXMLData("DAY_LJYQ_OVER",1);
				break;
			default:
				break;
			}
			
			return true;
		}
	}
	
	return false;
}

// 组装活跃值说明字符串
String GameCommonConfigManager::GetActivityDescString(String strJson, const uint32 & type, const uint32 & count, const uint32 & value)
{
	Json::Value val;
	Json::Reader reader;
	reader.parse(strJson, val);
	
	if(val.empty())
		return "";
	
	for (Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal)["type"].asUInt() == type)
		{
			char buf[256] = "";
			sprintf(buf, (*iterVal)["desc"].asString().c_str(), count, value);
			
			String strData = buf;
			return strData;
		}
	}
	
	return "";
}

/* [{
	"type": 1,
	"type_name": "新手任务",
	"items": [{
		"msid": 1000,
		"num": 10000
	}, {
		"msid": 1024,
		"num": 100
	}, {
		"msid": 1050,
		"num": 10
	}],
	"missions": [{
		"index": 1,
		"name": "首胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "任意场赢一次",
		"register_day": 1,
		"sub_type": 1
	}, {
		"index": 2,
		"name": "大胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "初级房及以上赢5局",
		"register_day": 1,
		"sub_type": 1
	}, {
		"index": 3,
		"name": "实名认证",
		"max_count": 1,
		"content": "完成实名认证",
		"register_day": 1,
		"sub_type": 5
	}, {
		"index": 4,
		"name": "旗开得胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "初级房及以上赢20局",
		"register_day": 2,
		"sub_type": 1,
		"need_complate": "3,2,1"
	}, {
		"index": 5,
		"name": "策划没填-累胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "高级房及以上累计赢取30万",
		"register_day": 2,
		"sub_type": 2,
		"need_complate": "3,2,1"
	}, {
		"index": 6,
		"name": "策划没填-连胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "高级房及以上连胜3场",
		"register_day": 2,
		"sub_type": 3,
		"need_complate": "3,2,1"
	}]
}, {
	"type": 2,
	"type_name": "引导任务",
	"missions": [{
		"index": 1,
		"items": [{
			"msid": 1000,
			"num": 50
		}],
		"name": "实名认证",
		"max_count": 1,
		"content": "完成实名认证",
		"sub_type": 5
	}, {
		"index": 2,
		"items": [{
			"msid": 1000,
			"num": 50
		}],
		"name": "绑定手机",
		"max_count": 1,
		"content": "完成手机绑定",
		"sub_type": 6
	}, {
		"index": 3,
		"items": [{
			"msid": 1000,
			"num": 50
		}],
		"name": "修改昵称",
		"max_count": 1,
		"content": "完成昵称修改",
		"sub_type": 7
	}]
}, {
	"type": 3,
	"type_name": "普通任务",
	"missions": [{
		"daily": 1,
		"index": 1,
		"items": [{
			"msid": 1000,
			"num": 50
		}],
		"name": "累计胜利",
		"logic_gzid": 441,
		"max_count": 10,
		"content": "在斗地主中累计胜利10局",
		"sub_type": 1
	}]
}] */

//===========================任务配置相关==========================
void GameCommonConfigManager::UpdateMissionConfig(stGameCommonConfig stGCC)
{
	if(stGCC.config_id == 0)
		return ;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(stGCC.sdata1, val);
	
	if(val.empty())
		return ;
	
	std::vector<stCommonGroupMissionConfig> vCGMC;
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		stCommonGroupMissionConfig stCGMC;
		stCGMC.type = (*iterVal)["type"].asUInt();
		// stCGMC.status = 1;	// 配置不需要填
		if((*iterVal).isMember("items"))
		{// 有打包奖励
			for(Json::Value::iterator iterItems=(*iterVal)["items"].begin(); iterItems!=(*iterVal)["items"].end(); ++iterItems)
			{
				stCGMC.items.insert(std::make_pair((*iterItems)["msid"].asUInt(), (*iterItems)["num"].asUInt()));	
			}
		}
		
		if((*iterVal).isMember("missions"))
		{// 里面包含的任务
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				stCommonSingleMissionConfig stCSMC;
				
				stCSMC.type = stCGMC.type;
				stCSMC.index = (*iterMissions)["index"].asUInt();
				stCSMC.sub_type = (*iterMissions)["sub_type"].asUInt();
				stCSMC.bounty_mode = 1;	// 奖励类型（1 主动领 2 被动发）
				stCSMC.need_count = (*iterMissions)["max_count"].asUInt();			// 最大需求进度
				
				if((*iterMissions).isMember("logic_gzid"))
					stCSMC.logic_gzid = (*iterMissions)["logic_gzid"].asUInt();		// 逻辑生效分区（0 表示所有分区都生效）
				
				if((*iterMissions).isMember("register_day"))
					stCSMC.register_day = (*iterMissions)["register_day"].asUInt();	// 逻辑生效分区（0 表示所有分区都生效）
				
				if((*iterMissions).isMember("daily"))
					stCSMC.daily = (*iterMissions)["daily"].asUInt();				// 日常(0 否 1 是）
				
				if((*iterMissions).isMember("identity") && (*iterMissions)["identity"].asUInt())
					stCSMC.identity = (*iterMissions)["identity"].asUInt();			// 是否指定身份（0 否 1 地主 2 农民）
				
				if((*iterMissions).isMember("base_coins") && (*iterMissions)["base_coins"].asUInt())
					stCSMC.base_coins = (*iterMissions)["base_coins"].asUInt();		// 是否指定场次（0 否 具体底分来判断）
				
				if((*iterMissions).isMember("name"))
					stCSMC.name = (*iterMissions)["name"].asString();					// 任务名称
				
				if((*iterMissions).isMember("content"))
					stCSMC.content = (*iterMissions)["content"].asString();			// 任务内容
				
				if((*iterMissions).isMember("need_complate"))
				{// 完成前置条件
					std::vector<String> vStr = StringUtil::split((*iterMissions)["need_complate"].asString(), ",");
					std::vector<String>::iterator itStr, eiStr = vStr.end();
					for(itStr = vStr.begin(); itStr!=eiStr; ++itStr)
					{
						stCSMC.vNeedComplate.push_back(StringConverter::parseUnsignedInt(*itStr));
					}
				}
				
				if((*iterMissions).isMember("items"))
				{// 完成获得的奖励
					for(Json::Value::iterator iterItems=(*iterMissions)["items"].begin(); iterItems!=(*iterMissions)["items"].end(); ++iterItems)
					{
						stCSMC.items.insert(std::make_pair((*iterItems)["msid"].asUInt(), (*iterItems)["num"].asUInt()));	
					}
				}
				
				stCGMC.missions.insert(std::make_pair(stCSMC.index, stCSMC));
			}
		}
		
		Log.Debug("GameCommonConfigManager::UpdateMissionConfig","agent_id[%u] type[%u]", stGCC.agent_id, stCGMC.type);
		vCGMC.push_back(stCGMC);
	}
	
	std::map<uint32, std::vector<stCommonGroupMissionConfig> >::iterator fit = m_mapCommonMission.find(stGCC.agent_id);
	if(fit == m_mapCommonMission.end())
	{// 没有就添加
		m_mapCommonMission.insert(std::make_pair(stGCC.agent_id, vCGMC));
	}
	else
	{// 有数据就更新
		fit->second = vCGMC;
	}
}

// 福袋奖励配置
void GameCommonConfigManager::UpdateFuDaiConfig(stGameCommonConfig stGCC)
{
	Json::Value val;
	Json::Reader reader;
	reader.parse(stGCC.sdata1, val);
	
	if(val.empty())
		return ;
	
	std::vector<stFuDaiConfig> vFC;
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		stFuDaiConfig stFC;
		stFC.index = (*iterVal)["index"].asUInt();
		stFC.percent = (*iterVal)["percent"].asUInt();
		for(Json::Value::iterator iterFuDai=(*iterVal)["items"].begin(); iterFuDai!=(*iterVal)["items"].end(); ++iterFuDai)
		{
			stFC.items.insert(std::make_pair((*iterFuDai)["msid"].asUInt(), (*iterFuDai)["num"].asUInt()));
		}
		
		vFC.push_back(stFC);
	}
	
	std::map<uint32, std::vector<stFuDaiConfig> >::iterator fit = m_mapCommonFuDai.find(stGCC.agent_id);
	if(fit == m_mapCommonFuDai.end())
	{// 没有就添加
		m_mapCommonFuDai.insert(std::make_pair(stGCC.agent_id, vFC));
	}
	else
	{// 有数据就更新
		fit->second = vFC;
	}
	
	std::map<uint32, uint32>::iterator fitModel = m_mapFuDaiModels.find(stGCC.agent_id);
	if(fitModel == m_mapFuDaiModels.end())
	{// 没有就添加
		m_mapFuDaiModels.insert(std::make_pair(stGCC.agent_id, stGCC.data1));
	}
	else
	{// 有数据就更新
		fitModel->second = stGCC.data1;
	}
}

// 获得福袋道具模式ID
uint32 GameCommonConfigManager::GetFuDaiModelID(CharPtr & pChr)
{
	if(pChr.isNull())
		return 0;
	
	AICreatureBaseInterface * pChrAiInfe = TO_CREATURE_BASE_INTERFACE(pChr->getAIInterface());
	if(!pChrAiInfe)
		return 0;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return 0;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	uint32 agent_id = pUser->getUInt32Field("reg_from");
	
WGS_CONFIG_LOCK
	stGameCommonConfig cc;
	if(!GetGameCommonConfig(agent_id, enGameCommonConfigType_FuDai, &cc))
		return 0;
	
	// 充值多少给一个福袋
	uint32 fudai_chongzhi = cc.data2;
	uint32 fudai_modelid = 0;
	std::map<uint32, uint32>::iterator fitMI = m_mapFuDaiModels.find(agent_id);
	if(fitMI != m_mapFuDaiModels.end())
		fudai_modelid = fitMI->second;
	else
		return 0;
	// /platform/getinvitedpayamount
	
	String strTitle = sXmlDataMgr.GetGatewayHttpHostAddr(agent_id)/* "open.dev.8z.net:60001" */;
	strTitle += "/platform/getinvitedpayamount";
	
    // pid
	// sig = md5(pid + key)
	
	// pid
	pid = 1000005;
	String strUrl = "pid=";
	strUrl += StringConverter::toString(pid);
	
	// 签名
	strUrl += "&sig=";
	CMD5 md5;
	strUrl += md5.GenerateMD5(StringConverter::toString(pid) + SERVERINFO_URL_SECRET);
	
	Log.Debug("GameCommonConfigManager::GetFuDaiModelID","strTitle[%s] strUrl[%s]", strTitle.c_str(), strUrl.c_str());
	String recv_result = httpd_request(strTitle, REQUIRE_URL_TIMEOUT, "POST", strUrl.c_str());
	Log.Debug("GameCommonConfigManager::GetFuDaiModelID","recv_result[%s]", recv_result.c_str());
	
	try
	{
		Json::Value valRet;
		Json::Reader reader;
		reader.parse(recv_result, valRet);
		
		String strFuDaiCount = pChrAiInfe->GetStringXMLData("GET_FUDAI_COUNT");
		Json::Value valGetFuDai;
		reader.parse(strFuDaiCount, valGetFuDai);
		
		if(valRet.isMember("ret") && valRet["ret"].asUInt() == 1)
		{
			if(valRet.isMember("data"))
			{
				bool bChangeData = false;
				for(Json::Value::iterator iterVal=valRet["data"].begin(); iterVal!=valRet["data"].end(); ++iterVal)
				{
					uint32 pid = 0;
					if((*iterVal)["pid"].isString())
						pid = StringConverter::parseUnsignedInt((*iterVal)["pid"].asString());
					else						
						pid = (*iterVal)["pid"].asUInt();
					
					uint32 pay = 0;
					if((*iterVal)["pay"].isString())
						pay = uint32(StringConverter::parseReal((*iterVal)["pay"].asString()));
					else
						pay = uint32((*iterVal)["pay"].asFloat());
					
					bool bFind = false;
					for(Json::Value::iterator iterGet=valGetFuDai.begin(); iterGet!=valGetFuDai.end(); ++iterGet)
					{
						if((*iterGet)["pid"].asUInt() == pid)
						{
							uint32 get_count = pay / fudai_chongzhi;
							if(get_count > (*iterGet)["get"].asUInt())
							{
								uint32 add_count = get_count - (*iterGet)["get"].asUInt();
								
								sGLMgr.addItemNum(pChr, fudai_modelid, add_count);
								sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_TuiGuangBuy, fudai_modelid, en_UNT_Add, add_count, 0, pid);
								bChangeData = true;
								
								(*iterGet)["get"] = get_count;
								Log.Debug("GameCommonConfigManager::GetFuDaiModelID","char[%u] give pid[%u] give count[%u] org_count[%u]", pChr->getHandle(), pid, get_count, get_count - add_count);
							}
							
							bFind = true;
							break;
						}
					}
					
					if(!bFind)
					{
						Json::Value valNew;
						valNew["pid"] = pid;
						
						uint32 get_count = pay / fudai_chongzhi;
						if(get_count > 0)
						{
							sGLMgr.addItemNum(pChr, fudai_modelid, get_count);
							sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_TuiGuangBuy, fudai_modelid, en_UNT_Add, get_count, 0, pid);
							Log.Debug("GameCommonConfigManager::GetFuDaiModelID","char[%u] give new pid[%u] give new count[%u]", pChr->getHandle(), pid, get_count);
						}
						
						valNew["get"] = get_count;
						valGetFuDai.append(valNew);
						
						bChangeData = true;
					}
					
				}
				
				if(bChangeData)
				{
					Json::FastWriter w;
					strFuDaiCount = w.write(valGetFuDai);
					
					pChrAiInfe->SetStringXMLData("GET_FUDAI_COUNT", strFuDaiCount);
				}
			}
		}
	}
	catch(exception &e)
	{
		return 0;
	}
	
	std::map<uint32, uint32>::iterator fit = m_mapFuDaiModels.find(agent_id);
	if(fit != m_mapFuDaiModels.end())
		return fit->second;
	
	return 0;
}

// 获得福袋奖励
std::map<uint32, uint32> GameCommonConfigManager::OpenFuDai(const uint32 & agent_id)
{
WGS_CONFIG_LOCK
	std::map<uint32, uint32> temp;
	std::map<uint32, std::vector<stFuDaiConfig> >::iterator fit = m_mapCommonFuDai.find(agent_id);
	if(fit == m_mapCommonFuDai.end())
		return temp;
	
	float percent = RandomFloat(0.0f, 1.0f);
	float curr_percent = 0.0f;
	std::vector<stFuDaiConfig>::iterator iter, ei = fit->second.end();
	for(iter = fit->second.begin(); iter!=ei; ++iter)
	{
		curr_percent += (*iter).percent;
		if(percent <= curr_percent)
		{
			return (*iter).items;
		}
	}
	
	return temp;
}

// =======================任务相关========================
// 添加任务
bool GameCommonMissionManager::AddGameCommonMission(stCommonMission & cm)
{
	Fields fields;
	sDataMgr.initData(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONMISSION, &fields);
	
	// fields["mission_id"] = cm.mission_id;
	fields["status"] = 1;
	fields["agent_id"] = cm.agent_id;
	fields["pid"] = cm.pid;
	fields["game_id"] = cm.game_id;
	fields["gz_id"] = cm.gz_id;
	
	fields["data1"] = cm.data1;
	fields["data2"] = cm.data2;
	fields["data3"] = cm.data3;
	fields["data4"] = cm.data4;
	fields["data5"] = cm.data5;
	fields["data6"] = cm.data6;
	fields["data7"] = cm.data7;
	fields["data8"] = cm.data8;
	
	fields["data_list"] = cm.data_list;
	fields["model_list"] = cm.model_list;
	
	fields["sdata1"] = cm.sdata1;
	fields["sdata2"] = cm.sdata2;
	fields["sdata3"] = cm.sdata3;
	fields["sdata4"] = cm.sdata4;
	fields["sdata5"] = cm.sdata5;
	fields["sdata6"] = cm.sdata6;
	fields["sdata7"] = cm.sdata7;
	fields["sdata8"] = cm.sdata8;
	
	fields["last_update_time"] = cm.last_update_time;
	fields["create_time"] = cm.create_time;
	
	if (!sDataMgr.insertData(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONMISSION, &fields))
		return false;
	
	cm.mission_id = fields["mission_id"].GetUInt32();
	return true;
}

// 更新任务
bool GameCommonMissionManager::UpdateGameCommonMission(const stCommonMission & cm)
{
	Fields fields;
	fields["status"] = cm.status;
	fields["agent_id"] = cm.agent_id;
	fields["pid"] = cm.pid;
	fields["game_id"] = cm.game_id;
	fields["gz_id"] = cm.gz_id;
	
	fields["data1"] = cm.data1;
	fields["data2"] = cm.data2;
	fields["data3"] = cm.data3;
	fields["data4"] = cm.data4;
	fields["data5"] = cm.data5;
	fields["data6"] = cm.data6;
	fields["data7"] = cm.data7;
	fields["data8"] = cm.data8;
	
	fields["data_list"] = cm.data_list;
	fields["model_list"] = cm.model_list;
	
	fields["sdata1"] = cm.sdata1;
	fields["sdata2"] = cm.sdata2;
	fields["sdata3"] = cm.sdata3;
	fields["sdata4"] = cm.sdata4;
	fields["sdata5"] = cm.sdata5;
	fields["sdata6"] = cm.sdata6;
	fields["sdata7"] = cm.sdata7;
	fields["sdata8"] = cm.sdata8;
	
	fields["last_update_time"] = cm.last_update_time;
	fields["create_time"] = cm.create_time;
	
	int count = sDataMgr.updateDataQueryAffected(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONMISSION, &fields, "`mission_id` = %u", cm.mission_id);
	return count > 0;
}

// 获取任务
bool GameCommonMissionManager::GetGameCommonMission(const uint32 & pid, stCommonMission * cm)
{
	assert (cm);
	FieldRows rows;
	sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONMISSION, &rows, "`status` < 255 and `pid` = %u", pid);
	if (rows.empty())
		return false;
	
	Fields fields = rows.front();
	cm->mission_id = fields["mission_id"].GetUInt32();
	cm->status = fields["status"].GetUInt32();
	cm->agent_id = fields["agent_id"].GetUInt32();
	cm->pid = fields["pid"].GetUInt32();
	cm->game_id = fields["game_id"].GetUInt32();
	cm->gz_id = fields["gz_id"].GetUInt32();
	
	cm->data1 = fields["data1"].GetInt32();
	cm->data2 = fields["data2"].GetInt32();
	cm->data3 = fields["data3"].GetInt32();
	cm->data4 = fields["data4"].GetInt32();
	cm->data5 = fields["data5"].GetInt32();
	cm->data6 = fields["data6"].GetInt32();
	cm->data7 = fields["data7"].GetInt32();
	cm->data8 = fields["data8"].GetInt32();
	
	cm->data_list = fields["data_list"].GetValue();
	cm->model_list = fields["model_list"].GetValue();
	
	cm->sdata1 = fields["sdata1"].GetValue();
	cm->sdata2 = fields["sdata2"].GetValue();
	cm->sdata3 = fields["sdata3"].GetValue();
	cm->sdata4 = fields["sdata4"].GetValue();
	cm->sdata5 = fields["sdata5"].GetValue();
	cm->sdata6 = fields["sdata6"].GetValue();
	cm->sdata7 = fields["sdata7"].GetValue();
	cm->sdata8 = fields["sdata8"].GetValue();
	
	cm->last_update_time = fields["last_update_time"].GetValue();
	cm->create_time = fields["create_time"].GetValue();
	return true;
}

// 获取任务列表
uint32 GameCommonMissionManager::GetGameCommonMissionList(std::list<stCommonMission> * lstData, const char * query,...)
{
	va_list argp;
	va_start(argp, query);
	lstData->clear();
	FieldRows fieldRows;
	
	char sql[SQLBUFER_LEN] = ""; 
	va_list vlist; 
	va_start(vlist, query); 
	vsnprintf(sql, SQLBUFER_LEN, query, vlist); 
	va_end(vlist);
	
	if (!sDataMgr.getDatas(DataManager::DatabaseTypeCenter, DB_NAME_GAMECOMMONMISSION, &fieldRows, sql))
		return 0;
	
	FieldRows::iterator iter, enditer = fieldRows.end();
	for (iter = fieldRows.begin(); iter != enditer; ++ iter)
	{
		stCommonMission cm;
		Fields &fields = *iter;
		cm.mission_id = fields["mission_id"].GetUInt32();
		cm.status = fields["status"].GetUInt32();
		cm.agent_id = fields["agent_id"].GetUInt32();
		cm.pid = fields["pid"].GetUInt32();
		cm.game_id = fields["game_id"].GetUInt32();
		cm.gz_id = fields["gz_id"].GetUInt32();
		
		cm.data1 = fields["data1"].GetInt32();
		cm.data2 = fields["data2"].GetInt32();
		cm.data3 = fields["data3"].GetInt32();
		cm.data4 = fields["data4"].GetInt32();
		cm.data5 = fields["data5"].GetInt32();
		cm.data6 = fields["data6"].GetInt32();
		cm.data7 = fields["data7"].GetInt32();
		cm.data8 = fields["data8"].GetInt32();
		
		cm.data_list = fields["data_list"].GetValue();
		cm.model_list = fields["model_list"].GetValue();
		
		cm.sdata1 = fields["sdata1"].GetValue();
		cm.sdata2 = fields["sdata2"].GetValue();
		cm.sdata3 = fields["sdata3"].GetValue();
		cm.sdata4 = fields["sdata4"].GetValue();
		cm.sdata5 = fields["sdata5"].GetValue();
		cm.sdata6 = fields["sdata6"].GetValue();
		cm.sdata7 = fields["sdata7"].GetValue();
		cm.sdata8 = fields["sdata8"].GetValue();
		
		cm.last_update_time = fields["last_update_time"].GetValue();
		cm.create_time = fields["create_time"].GetValue();
		lstData->push_back(cm);
	}
	
	return lstData->size();
}


/* [{
	"type": 1,
	"type_name": "新手任务",
	"items": [{
		"msid": 1000,
		"num": 10000
	}, {
		"msid": 1024,
		"num": 100
	}, {
		"msid": 1050,
		"num": 10
	}],
	"missions": [{
		"index": 1,
		"name": "首胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "任意场赢一次",
		"register_day": 1,
		"sub_type": 1
	}, {
		"index": 2,
		"name": "大胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "初级房及以上赢5局",
		"register_day": 1,
		"sub_type": 1
	}, {
		"index": 3,
		"name": "实名认证",
		"max_count": 1,
		"content": "完成实名认证",
		"register_day": 1,
		"sub_type": 5
	}, {
		"index": 4,
		"name": "旗开得胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "初级房及以上赢20局",
		"register_day": 2,
		"sub_type": 1,
		"need_complate": "3,2,1"
	}, {
		"index": 5,
		"name": "策划没填-累胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "高级房及以上累计赢取30万",
		"register_day": 2,
		"sub_type": 2,
		"need_complate": "3,2,1"
	}, {
		"index": 6,
		"name": "策划没填-连胜",
		"logic_gzid": 441,
		"max_count": 1,
		"content": "高级房及以上连胜3场",
		"register_day": 2,
		"sub_type": 3,
		"need_complate": "3,2,1"
	}]
}, {
	"type": 2,
	"type_name": "引导任务",
	"missions": [{
		"index": 1,
		"items": [{
			"msid": 1000,
			"num": 50
		}],
		"name": "实名认证",
		"max_count": 1,
		"content": "完成实名认证",
		"sub_type": 5
	}, {
		"index": 2,
		"items": [{
			"msid": 1000,
			"num": 50
		}],
		"name": "绑定手机",
		"max_count": 1,
		"content": "完成手机绑定",
		"sub_type": 6
	}, {
		"index": 3,
		"items": [{
			"msid": 1000,
			"num": 50
		}],
		"name": "修改昵称",
		"max_count": 1,
		"content": "完成昵称修改",
		"sub_type": 7
	}]
}, {
	"type": 3,
	"type_name": "普通任务",
	"missions": [{
		"daily": 1,
		"index": 1,
		"items": [{
			"msid": 1000,
			"num": 50
		}],
		"name": "累计胜利",
		"logic_gzid": 441,
		"max_count": 10,
		"content": "在斗地主中累计胜利10局",
		"sub_type": 1
	}]
}] */

// ========================任务逻辑部分============================
// 获得玩家任务（如果没有就创建）
bool GameCommonMissionManager::GetPlayerCommonMission(CharPtr & pChr, stCommonMission * cm, bool bSameDay)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.load(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	uint32 gz_id = pUser->getUInt32Field("gz_id");
	uint32 agent_id = pUser->getUInt32Field("reg_from");
	uint32 game_id = sGLMgr.GetTargetServerGameid(gz_id, agent_id);
	
	if(!GetGameCommonMission(pid, cm))
	{// 玩家没得任务，创建任务数据
		// 初始任务数据列表
		std::map<uint32, std::vector<stCommonGroupMissionConfig> > mapCommonMission = sGameCommonConfigMgr.GetCommonMissionConfig();
		std::map<uint32, std::vector<stCommonGroupMissionConfig> >::iterator fit = mapCommonMission.find(agent_id);
		if(fit == mapCommonMission.end())
			return false;
		
		cm->status = 1;
		cm->agent_id = agent_id;
		cm->pid = pid;
		cm->game_id = game_id;
		cm->gz_id = gz_id;
		
		Json::Value valList;
		
		std::vector<stCommonGroupMissionConfig> vMissions = fit->second;
		std::vector<stCommonGroupMissionConfig>::iterator iter, ei = vMissions.end();
		for(iter = vMissions.begin(); iter!=ei; ++iter)
		{
			Json::Value valGroup;
			valGroup["type"] = (*iter).type;
			valGroup["status"] = enCommonMissionStatus_Process;
			
			// 奖励列表
			std::map<uint32, uint32>::iterator iterItems, eiItems = (*iter).items.end();
			for(iterItems = (*iter).items.begin(); iterItems!=eiItems; ++iterItems)
			{
				Json::Value valItem;
				valItem["msid"] = iterItems->first;
				valItem["num"] = iterItems->second;
				
				valGroup["items"].append(valItem);
			}
			
			// 任务列表
			std::map<uint32, stCommonSingleMissionConfig>::iterator iterMissions, eiMissions = (*iter).missions.end();
			for(iterMissions = (*iter).missions.begin(); iterMissions!=eiMissions; ++iterMissions)
			{Json::Value valMission;
				valMission["sub_type"] = iterMissions->second.sub_type;
				valMission["status"] = enCommonMissionStatus_Process;
				valMission["curr_count"] = 0;
				valMission["need_count"] = iterMissions->second.need_count;
				valMission["logic_gzid"] = iterMissions->second.logic_gzid;
				valMission["register_day"] = iterMissions->second.register_day;
				valMission["daily"] = iterMissions->second.daily;
				valMission["name"] = iterMissions->second.name;
				valMission["content"] = iterMissions->second.content;
				
				// 任务奖励列表
				std::map<uint32, uint32>::iterator itMissItems, eiMissItems = iterMissions->second.items.end();
				for(itMissItems = iterMissions->second.items.begin(); itMissItems!=eiMissItems; ++itMissItems)
				{
					Json::Value valMissItem;
					valMissItem["msid"] = itMissItems->first;
					valMissItem["num"] = itMissItems->second;
					
					valMission["items"].append(valMissItem);
				}
				
				valGroup["missions"].append(valMission);
				
				// 需要前置完成任务
				String strNeedComplate = "";
				std::vector<uint32>::iterator itNC, eiNC = iterMissions->second.vNeedComplate.end();
				for(itNC = iterMissions->second.vNeedComplate.begin(); itNC!=eiNC; ++itNC)
				{
					strNeedComplate += StringConverter::toString(*itNC);
					strNeedComplate += ",";
				}
				
				valGroup["need_complate"] = strNeedComplate;
			}
			
			valList.append(valGroup);
		}
		
		Json::FastWriter w;
		cm->data_list = w.write(valList);
		
		cm->create_time = sGLMgr.GetCurDateTime();
		cm->last_update_time = cm->create_time;
		
		AddGameCommonMission(*cm);
	}
	else
	{// 更改数据
		Json::Value valList;
		Json::Reader reader;
		reader.parse(cm->sdata1, valList);
		
		bool bChangeData = false;
		for(Json::Value::iterator iterVal=valList.begin(); iterVal!=valList.end(); ++iterVal)
		{
			if((*iterVal)["type"].asUInt() == 1)
			{// 新手有时效的任务
				uint32 max_registerDay = 0;
				if((*iterVal).isMember("missions"))
				{
					for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
					{
						if((*iterMissions).isMember("register_day"))
						{
							if(max_registerDay < (*iterMissions)["register_day"].asUInt())
								max_registerDay = (*iterMissions)["register_day"].asUInt();
						}
					}
				}
				
				uint32 off_days = sTools.GetOffsetDate(pUser->getUInt32Field("ll_time"), time(0));
				if(off_days >= max_registerDay)
				{
					(*iterVal)["status"] = enCommonMissionStatus_TimesUp;
					bChangeData = true;
				}
			}
			else if((*iterVal)["type"] == 3)
			{// 普通日常任务
				if((*iterVal).isMember("missions"))
				{
					for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
					{
						if((*iterMissions)["daily"].asUInt() == 1)
						{// 每日任务状态重置为进行中
							(*iterMissions)["status"] = enCommonMissionStatus_Process;
							bChangeData = true;
						}
					}
				}
			}
		}
		
		if(bChangeData)
		{
			Json::FastWriter w;
			cm->sdata1 = w.write(valList);
			
			UpdateGameCommonMission(*cm);
		}
	}
	
	return true;
}

// 检测任务附加条件
bool GameCommonMissionManager::CheckMissionExtraParams(Json::Value valMission, Json::Value valParams, Json::Value valMissionData, const uint32 & reg_time, const uint32 & curr_time)
{
	if(valMission.isMember("identity") && valMission["identity"].asUInt())
	{// 有指定身份
		if(!valParams.isMember("identity"))
			return false;
		
		if(valParams["identity"].asUInt() != valMission["identity"].asUInt())
			return false;
	}
	
	if(valMission.isMember("base_coins") && valMission["base_coins"].asUInt())
	{// 有指定场次，通过底分来判断
		if(!valParams.isMember("base_coins"))
			return false;
		
		if(valParams["base_coins"].asUInt() < valMission["base_coins"].asUInt())
			return false;
	}
	
	// 注册天数检测逻辑
	uint8 register_day = 0;
	if(valMission.isMember("register_day"))
	{
		register_day = valMission["register_day"].asUInt();
		if(register_day)
		{// 注册需求天数未到，无法完成任务
			uint32 off_days = sTools.GetOffsetDate(reg_time, curr_time) + 1;
			if(off_days < register_day)
				return false;
		}
	}
	
	// 前置任务检查"3,2,1,"
	String strNeedComplate = "";
	if(valMission.isMember("need_complate"))
	{
		strNeedComplate = valMission["need_complate"].asString();
		
		std::vector<uint32> vIntNC;
		
		std::vector<String> vStrNC = StringUtil::split(strNeedComplate, ",");
		std::vector<String>::iterator itNC, eiNC = vStrNC.end();
		for(itNC = vStrNC.begin(); itNC!=eiNC; ++itNC)
		{
			vIntNC.push_back(StringConverter::parseUnsignedInt(*itNC));
		}
		
		if(vIntNC.size())
		{
			for(Json::Value::iterator iterVal2=valMissionData.begin(); iterVal2!=valMissionData.end(); ++iterVal2)
			{
				if((*iterVal2).isMember("missions"))
				{
					for(Json::Value::iterator iterMissions2=(*iterVal2)["missions"].begin(); iterMissions2!=(*iterVal2)["missions"].end(); ++iterMissions2)
					{
						std::vector<uint32>::iterator itINC, eiINC = vIntNC.end();
						for(itINC = vIntNC.begin(); itINC!=eiINC; ++itINC)
						{
							uint8 mission_status = (*iterMissions2)["status"].asUInt();
							if((*iterMissions2)["index"].asUInt() == *itINC && 
								(mission_status == enCommonMissionStatus_Finish || mission_status == enCommonMissionStatus_GetBounty))
							{
								vIntNC.erase(itINC);
								break;
							}
						}
					}
				}
			}
			
			if(vIntNC.size())
			{// 还有前置任务没有完成
				return false;
			}
		}
	}
	
	return true;
}
	
// 累计胜利局数任务 (pChr 角色 count 局数 strData 附加参数)
bool GameCommonMissionManager::ComplateCountWinCountMission(CharPtr & pChr, const uint32 & count, Json::Value & valParams)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	uint32 time_now = time(0);
	
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计胜利任务
				if((*iterMissions)["sub_type"].asUInt() != enCommonMissionSubType_CountWinCount)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				// 条件判断未通过
				if(!CheckMissionExtraParams(*iterMissions, valParams, val, pUser->getUInt32Field("reg_time"), time_now))
					continue;
				
				(*iterMissions)["curr_count"] = (*iterMissions)["curr_count"].asUInt() + count;
				if((*iterMissions)["curr_count"].asUInt() >= (*iterMissions)["need_count"].asUInt())
				{// 任务完成 状态更新 通知客户端
					
					if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
						(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;	// 新手任务直接标记为已领取
					else
						(*iterMissions)["status"] = enCommonMissionStatus_Finish;		// 其他任务标记为可领
					
					WorldPacket packet;
					if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), (*iterMissions)["status"].asUInt()))
						sGLMgr.SendProtocolsToChr(pChr, &packet);
					break;
				}
				
			}
		}
	}
	
	return true;
}
	
// 累计赢取游戏币任务 (pChr 角色 count 局数 strData 附加参数)
bool GameCommonMissionManager::ComplateCountWinCoinsMission(CharPtr & pChr, const uint32 & count, Json::Value & valParams)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	uint32 time_now = time(0);
	
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计赢取任务
				if((*iterMissions)["sub_type"].asUInt() != enCommonMissionSubType_CountWinCoins)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				// 条件判断未通过
				if(!CheckMissionExtraParams(*iterMissions, valParams, val, pUser->getUInt32Field("reg_time"), time_now))
					continue;
				
				(*iterMissions)["curr_count"] = (*iterMissions)["curr_count"].asUInt() + count;
				if((*iterMissions)["curr_count"].asUInt() >= (*iterMissions)["need_count"].asUInt())
				{// 任务完成 状态更新 通知客户端
					
					if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
						(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;	// 新手任务直接标记为已领取
					else
						(*iterMissions)["status"] = enCommonMissionStatus_Finish;		// 其他任务标记为可领
					
					WorldPacket packet;
					if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), (*iterMissions)["status"].asUInt()))
						sGLMgr.SendProtocolsToChr(pChr, &packet);
					break;
				}
				
			}
		}
	}
	
	return true;
}

// 连续胜利局数
bool GameCommonMissionManager::ComplateComboWinCountMission(CharPtr & pChr, const uint32 & count, Json::Value & valParams)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	uint32 time_now = time(0);
	
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计赢取任务
				if((*iterMissions)["sub_type"].asUInt() != enCommonMissionSubType_ComboWinCount)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				// 条件判断未通过
				if(!CheckMissionExtraParams(*iterMissions, valParams, val, pUser->getUInt32Field("reg_time"), time_now))
					continue;
				
				if(count)
					(*iterMissions)["curr_count"] = (*iterMissions)["curr_count"].asUInt() + count;
				else
					(*iterMissions)["curr_count"] = 0;		// 连胜断掉
				
				if((*iterMissions)["curr_count"].asUInt() >= (*iterMissions)["need_count"].asUInt())
				{// 任务完成 状态更新 通知客户端
					
					if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
						(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;	// 新手任务直接标记为已领取
					else
						(*iterMissions)["status"] = enCommonMissionStatus_Finish;		// 其他任务标记为可领
					
					WorldPacket packet;
					if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), (*iterMissions)["status"].asUInt()))
						sGLMgr.SendProtocolsToChr(pChr, &packet);
					break;
				}
				
			}
		}
	}
	
	return true;
}

// 等级达成任务
bool GameCommonMissionManager::ComplateLevelUpMission(CharPtr & pChr, const uint32 & lv)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	uint32 time_now = time(0);
	
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计赢取任务
				if((*iterMissions)["sub_type"].asUInt() != enCommonMissionSubType_LevelUp)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				// 条件判断未通过
				Json::Value valParams;
				if(!CheckMissionExtraParams(*iterMissions, valParams, val, pUser->getUInt32Field("reg_time"), time_now))
					continue;
				
				if((*iterMissions)["curr_count"].asUInt() >= lv)
				{// 任务完成 状态更新 通知客户端
					
					if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
						(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;	// 新手任务直接标记为已领取
					else
						(*iterMissions)["status"] = enCommonMissionStatus_Finish;		// 其他任务标记为可领
					
					WorldPacket packet;
					if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), (*iterMissions)["status"].asUInt()))
						sGLMgr.SendProtocolsToChr(pChr, &packet);
					break;
				}
				
			}
		}
	}
	
	return true;
}

// 实名认证任务
bool GameCommonMissionManager::ComplateCertificationMission(CharPtr & pChr)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	uint32 time_now = time(0);
	
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计赢取任务
				if((*iterMissions)["sub_type"].asUInt() != enCommonMissionSubType_SetRealName)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				// 条件判断未通过
				Json::Value valParams;
				if(!CheckMissionExtraParams(*iterMissions, valParams, val, pUser->getUInt32Field("reg_time"), time_now))
					continue;
				
				if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
					(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;	// 新手任务直接标记为已领取
				else
					(*iterMissions)["status"] = enCommonMissionStatus_Finish;		// 其他任务标记为可领
				
				WorldPacket packet;
				if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), (*iterMissions)["status"].asUInt()))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
				break;
			}
		}
	}
	
	return true;
}

// 绑定手机任务
bool GameCommonMissionManager::ComplateBandPhoneMission(CharPtr & pChr)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	uint32 time_now = time(0);
	
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计赢取任务
				if((*iterMissions)["sub_type"].asUInt() != enCommonMissionSubType_BandPhone)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				// 条件判断未通过
				Json::Value valParams;
				if(!CheckMissionExtraParams(*iterMissions, valParams, val, pUser->getUInt32Field("reg_time"), time_now))
					continue;
				
				if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
					(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;	// 新手任务直接标记为已领取
				else
					(*iterMissions)["status"] = enCommonMissionStatus_Finish;		// 其他任务标记为可领
				
				WorldPacket packet;
				if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), (*iterMissions)["status"].asUInt()))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
				break;
			}
		}
	}
	
	return true;
}

// 修改昵称任务
bool GameCommonMissionManager::ComplateReNameMission(CharPtr & pChr)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	uint32 time_now = time(0);
	
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计赢取任务
				if((*iterMissions)["sub_type"].asUInt() != enCommonMissionSubType_ReName)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				// 条件判断未通过
				Json::Value valParams;
				if(!CheckMissionExtraParams(*iterMissions, valParams, val, pUser->getUInt32Field("reg_time"), time_now))
					continue;
				
				if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
					(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;	// 新手任务直接标记为已领取
				else
					(*iterMissions)["status"] = enCommonMissionStatus_Finish;		// 其他任务标记为可领
				
				WorldPacket packet;
				if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), (*iterMissions)["status"].asUInt()))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
				break;
			}
		}
	}
	
	return true;
}

// 累计游戏次数任务
bool GameCommonMissionManager::ComplateCountPlayerCount(CharPtr & pChr, const uint32 & count, Json::Value & valParams)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	uint32 time_now = time(0);
	
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计胜利任务
				if((*iterMissions)["sub_type"].asUInt() != enCommonMissionSubType_CountPlayerCount)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				// 条件判断未通过
				if(!CheckMissionExtraParams(*iterMissions, valParams, val, pUser->getUInt32Field("reg_time"), time_now))
					continue;
				
				(*iterMissions)["curr_count"] = (*iterMissions)["curr_count"].asUInt() + count;
				if((*iterMissions)["curr_count"].asUInt() >= (*iterMissions)["need_count"].asUInt())
				{// 任务完成 状态更新 通知客户端
					
					if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
						(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;	// 新手任务直接标记为已领取
					else
						(*iterMissions)["status"] = enCommonMissionStatus_Finish;		// 其他任务标记为可领
					
					WorldPacket packet;
					if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), (*iterMissions)["status"].asUInt()))
						sGLMgr.SendProtocolsToChr(pChr, &packet);
					break;
				}
				
			}
		}
	}
	
	return true;
}

// 领取任务奖励
bool GameCommonMissionManager::GetBounty(CharPtr & pChr, const uint32 & type, const uint32 & index)
{
	if(pChr.isNull())
		return false;
	
	uint8 result = enGetCommonMissionBounty_Sucess;
	stCommonMission cm;
	do
	{
		if(!GetPlayerCommonMission(pChr, &cm))
		{// 未找到任务数据
			result = enGetCommonMissionBounty_NoMission;
			break;
		}
		
		Json::Value val;
		Json::Reader reader;
		reader.parse(cm.sdata1, val);
		
		bool bFind = false;
		for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
		{
			if(type != (*iterVal)["type"].asUInt())
				continue;
			
			if(!(*iterVal).isMember("missions"))
				continue;
			
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				
				if((*iterMissions)["index"].asUInt() == index)
				{
					bFind = true;
					if((*iterMissions)["status"].asUInt() == enCommonMissionStatus_GetBounty)
					{// 已领取
						result = enGetCommonMissionBounty_GetAready;
						break;
					}
					else if((*iterMissions)["status"].asUInt() == enCommonMissionStatus_Process)
					{// 未完成
						result = enGetCommonMissionBounty_NoFinish;
						break;
					}
					
					(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;
					if((*iterMissions).isMember("items"))
					{
						for(Json::Value::iterator iterItems=(*iterVal)["items"].begin(); iterMissions!=(*iterVal)["items"].end(); ++iterItems)
						{
							uint32 model_id = (*iterItems)["msid"].asUInt();
							uint32 num = (*iterItems)["num"].asUInt();
							// 发放奖励
							sGLMgr.addItemNum(pChr, model_id, num);
							// 记录日志
							sLogDataMgr.UpdateItemsInfoLog(pChr, en_ST_Task, model_id, en_UNT_Add, num, 0, type, index);
						}
					}
				}
			}
			
			if(result != enGetCommonMissionBounty_Sucess)
				break;
		}
		
		if(!bFind)
		{// 未找到任务
			result = enGetCommonMissionBounty_NoMission;
			break;
		}
	}
	while(0);
	
	WorldPacket packet;
	if(sProtocolsMgr.CreateCommonConfigMissionGetPacket(&packet, type, index, result))
		sGLMgr.SendProtocolsToChr(pChr, &packet);
	
	Log.Debug("GameCommonMissionManager::GetBounty","char[%u] type[%u] index[%u] result[%u]", pChr->getHandle(), type, index, result);
	return true;
}


// 更新任务状态
bool GameCommonMissionManager::ClientUpdateMissionStatus(CharPtr & pChr, const uint32 & type, const uint32 & sub_type)
{
	if(pChr.isNull())
		return false;
	
	UserPtr pUser = sUserMgr.getByHandle(pChr->getUInt32Field("userid"));
	if(pUser.isNull())
		return false;
	
	uint32 pid = pUser->getUInt32Field("platform_id");
	
	stCommonMission cm;
	if(!GetGameCommonMission(pid, &cm))
		return false;
	
	Json::Value val;
	Json::Reader reader;
	reader.parse(cm.sdata1, val);
	
	if(val.empty())
		return false;
	
	bool bUpdateStatus = false;
	for(Json::Value::iterator iterVal=val.begin(); iterVal!=val.end(); ++iterVal)
	{
		if((*iterVal).isMember("missions"))
		{// 有任务列表
			for(Json::Value::iterator iterMissions=(*iterVal)["missions"].begin(); iterMissions!=(*iterVal)["missions"].end(); ++iterMissions)
			{
				// 不是累计胜利任务
				if((*iterMissions)["sub_type"].asUInt() != sub_type)
					continue;
				
				// 不是进行中任务 不需要更新
				if((*iterMissions)["status"].asUInt() != enCommonMissionStatus_Process)
					continue;
				
				if((*iterVal)["type"].asUInt() == enCommonMissionType_NewPlayerGroup)
					(*iterMissions)["status"] = enCommonMissionStatus_GetBounty;
				else
					(*iterMissions)["status"] = enCommonMissionStatus_Finish;
				
				bUpdateStatus = true;
				
				// 发包通知玩家任务状态更新
				WorldPacket packet;
				if(sProtocolsMgr.CreateCommonConfigMissionStatusUpdatePacket(&packet, (*iterVal)["type"].asUInt(), (*iterMissions)["index"].asUInt(), enCommonMissionStatus_Finish))
					sGLMgr.SendProtocolsToChr(pChr, &packet);
				break;
			}
		}
	}
	
	return bUpdateStatus;
}
